home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1998 July & August / Pcwk78a98.iso / Micrsoft / SAMPLES / VJ6SAMPL.EXE / BindPubs / BindPubs.java next >
Encoding:
Java Source  |  1998-02-24  |  9.8 KB  |  302 lines

  1.  
  2. /*  Copyright (C) Microsoft Corporation, 1996-1998.  All rights reserved.
  3.  
  4.   This source code is intended only as a supplement to Microsoft
  5.   Visual J++ 6.0.  See this product's on-line documentation for detailed   
  6. information regarding Microsoft code samples.
  7.  
  8. */
  9.  
  10. import wfc.app.*;
  11. import wfc.core.*;
  12. import wfc.ui.*;
  13. import wfc.util.*;
  14. import wfc.data.ui.*;
  15. import wfc.data.*;
  16. import splash.*;
  17.  
  18.  
  19. /**BindPubs creates a simple form with text 
  20.  * boxes bound to the authors table in the 
  21.  * pubs database and a set of navigation buttons
  22. */
  23. public class BindPubs extends Form implements ISplashable
  24. {
  25.     /**Default constructor creates form
  26.      */
  27.     public BindPubs()
  28.     {
  29.         SplashScreen splash = (new SplashScreen(this));
  30.         Label splashLabel = splash.getSplashLabel();
  31.         splashLabel.setFont(new Font("MS Sans Serif", 12));
  32.         splashLabel.setText("Initializing Main Form");
  33.         //call initForm() to set up form
  34.         initForm();        
  35.         //create buttons with which to navigate the recordset
  36.         splashLabel.setText("Creating Navigation Buttons");
  37.         //ensure there'll be enough width for the buttons
  38.         int minButtonWidth = 40;
  39.         for(int i=0;i<buttonLabels.length;i++)
  40.         {
  41.             Button nav = new Button();
  42.             nav.setText(buttonLabels[i]);
  43.             nav.addOnClick(new EventHandler(this.nav_click));
  44.             add(nav);
  45.             navButtons.addItem(nav);
  46.             nav.setWidth(buttonWidth);
  47.             minButtonWidth += nav.getWidth() + buttonPad;
  48.         } 
  49.         /*Create a new connection. There must be a dsn named pubs that logs on to a SQL server,
  50.         and defaults to a database that contains a table names authors
  51.          */
  52.         splashLabel.setText("Opening Connection to DataBase");
  53.         Connection pubs = new Connection("dsn=Pubs");
  54.         System.err.println(pubs.getConnectionString());
  55.         System.err.println(pubs.getProvider());
  56.         AdoProperties props = pubs.getProperties();
  57.         System.err.println(props);
  58.         for(int i=0;i<props.getCount();i++)
  59.             System.err.println(props.getItem(i).getName()+": "+props.getItem(i).getString());
  60.         //pubs.setDefaultDatabase("Pubs");
  61.         try 
  62.         {
  63.             pubs.open();
  64.         }
  65.         catch(AdoException e)
  66.         {
  67.             splashLabel.setText("Connection Failed");
  68.             Label error = new Label();
  69.             error.setText("Please check your connection to the database and DSN definition");
  70.             error.setBounds(getClientRect());
  71.             add(error);
  72.             return;
  73.         }
  74.         splashLabel.setText("Preparing for user query");
  75.         //Create and open a recordset that contains all of the authors table
  76.         authors = new Recordset();
  77.         authors.setCursorLocation(AdoEnums.CursorLocation.CLIENT);
  78.         authors.setActiveConnection(pubs);
  79.         
  80.         
  81.         //get the query string from the user (default to "select * from authors")
  82.         String query = "select * from authors";
  83.         InputBox queryBox = new InputBox("Enter a Structured Query Language (SQL)"+
  84.             "string with which to query the database", 
  85.             "Input Query String", query);
  86.         queryBox.bringToFront();
  87.         //make the splash screen invisible while the input box is up
  88.         splash.setVisible(false);
  89.         if(queryBox.showDialog()==DialogResult.OK)
  90.         {
  91.             query = queryBox.getResponse();
  92.         }
  93.         splash.setVisible(true);
  94.         splash.update();
  95.         splashLabel.setText("Retrieving Data");
  96.         try
  97.         {
  98.             authors.open(query);
  99.         }
  100.         catch(AdoException e)
  101.         {
  102.             String message = "Bad Query; Please Try Again\r"+e.getMessage();
  103.             String title = "Incorrect SQL Syntax or no table found";
  104.             int options = MessageBox.ICONWARNING;
  105.             new MessageBox().show(message, title, options);
  106.             dispose();
  107.         }
  108.         //keep the query that has been sent in the form's title bar
  109.         setText(query);
  110.         //append the number of records returned to the window title
  111.         setText(getText()+": "+String.valueOf(authors.getRecordCount())+" records");
  112.         int fieldCount=0;
  113.         try
  114.         {
  115.             fieldCount = authors.getFields().getCount();
  116.             //TODO: warn the user if no fields were returned
  117.         }
  118.         catch(Throwable t)
  119.         {
  120.             t.printStackTrace();
  121.             System.err.println(t.getMessage());
  122.         }
  123.         
  124.         splashLabel.setText("Binding Data to Edit Boxes");
  125.         //create a DataBinding array
  126.         DataBinding[] bindings = new DataBinding[fieldCount];
  127.         //create an edit for each field and bind it thereto
  128.         //ensure that the form is wide enough for the edit boxes
  129.         int minEditWidth = 80;
  130.         int editPad = 10;
  131.         for(int i=0;i<fieldCount;i++)
  132.         {
  133.             CaptionedEdit edit = new CaptionedEdit();
  134.             DataBinding binding = new DataBinding(edit, "text", authors.getField(i).getName());
  135.             bindings[i]=binding;
  136.             edit.setCaption(authors.getField(i).getName());
  137.             add(edit);
  138.             //keep a list of all the display edits
  139.             dispEdits.addItem(edit);
  140.             //the edit boxes should be at least 80 pixels wide
  141.             minEditWidth += 80 + editPad;
  142.         }
  143.         //lay all of the display edits side by side
  144.         int editCount = dispEdits.getSize();
  145.         
  146.         //set the width to be wide enough to hold the buttons and the edits
  147.         int formWidth = getWidth();
  148.         if(formWidth<minButtonWidth)
  149.             formWidth=minButtonWidth;
  150.         if(formWidth<minEditWidth)
  151.             formWidth = minEditWidth;
  152.         setWidth(formWidth);
  153.                 
  154.         //TIP: use this code if your form is wider than your screen
  155.         setAutoScroll(true);
  156.         setAutoScrollMargin(new Point(editMargin, 0));
  157.         //determine the spacing between edit boxes
  158.         int width = (getClientRect().width-(2*editMargin)-(editCount-1)*editPad)/editCount;
  159.         for(int i=0;i<editCount;i++)
  160.         {
  161.             Edit edit = ((Edit)(dispEdits.getItem(i)));
  162.             edit.setSize(width, 40);
  163.             edit.setLocation(editMargin+(width+editPad)*i, 20);
  164.         }    
  165.         
  166.         //bind the edits to the recordset
  167.         DataBinder binder = new DataBinder(authors, bindings);
  168.         try
  169.         {
  170.             authors.moveFirst();
  171.         }
  172.         catch(Throwable t)
  173.         {
  174.             System.err.println(t.getMessage());
  175.             t.printStackTrace();
  176.         }
  177.         bringToFront();
  178.     }
  179.  
  180.     /**
  181.      * The main entry point for the application. 
  182.      * Calls constructor and runs form
  183.      */
  184.     public static void main(String args[])
  185.     {
  186.         //Do the dataprocessing in the form's constructor, after the splashScreen is created
  187.         Application.run(new BindPubs());
  188.     }
  189.  
  190.     
  191.     int buttonPad = 20;
  192.     int buttonWidth = 80;
  193.     Recordset authors;
  194.     //create labels for the navigation buttons
  195.     String[] buttonLabels = {"First","Previous","Next","Last"};//TODO: Add Update Functionality
  196.     List navButtons = new List();
  197.     List dispEdits = new List();
  198.     int editMargin = 40;
  199.     private static int callLayout=0;
  200.     Container components = new Container();
  201.     /*TIP: creating a variable to hold the event handler allows you to remove it
  202.     or assign it to more than one element
  203.     */
  204.     private EventHandler layButtons = new EventHandler(this.form_resize);
  205.     private ThreadExceptionEventHandler ignoreGlobalException = new ThreadExceptionEventHandler(this.application_threadExcept);
  206.     /**Creates and places UI elements and properties of form
  207.     */
  208.     private void initForm()
  209.     {
  210.         this.setSize(100, 150);
  211.         this.setText ("BindPubs");
  212.         this.addOnResize(layButtons);
  213.         this.addOnClosed(new EventHandler(this.form_closed));
  214.     }
  215.     // NOTE: End of form designer support code
  216.     protected void form_closed(Object source, Event event)
  217.     {
  218.         //close the recordset
  219.         authors.close();
  220.         authors.getActiveConnection().close();
  221.         //release the recordset
  222.         authors = null;
  223.         //From here on in, I don't care about any exception
  224.         Application.addOnThreadException(ignoreGlobalException);
  225.     }
  226.     /**Called by any exception on the Application that happens after the form closes. The empty message body suppresses default behavior of the libraries
  227.      */
  228.     private void application_threadExcept(Object source, ThreadExceptionEvent event)
  229.     {
  230.         //Global Exceptions can take care of themselves
  231.     }
  232.     /**Called by clicking a navigation button. Moves around the recordset
  233.      */
  234.     protected void nav_click(Object source, Event event) throws RuntimeException
  235.     {
  236.         String label = ((Button)source).getText();
  237.         if(label.equals(buttonLabels[0]))//First
  238.             authors.moveFirst();
  239.         else if(label.equals(buttonLabels[1]))//Previous
  240.         {
  241.             //the data binding will cause movePrevious to throw uncatchable exceptions on BOF
  242.             //Application.addOnThreadException(ignoreGlobalException);
  243.             try 
  244.             {
  245.                 authors.movePrevious();
  246.             }
  247.             catch (AdoException e){}
  248.             //Application.removeOnThreadException(ignoreGlobalException);
  249.             if(authors.getBOF())
  250.                 authors.moveFirst();
  251.         }
  252.         else if(label.equals(buttonLabels[2]))//Next
  253.         {
  254.             //the data binding will cause moveNext to throw exceptions on EOF
  255.             try
  256.             {
  257.                 authors.moveNext();
  258.             }
  259.             catch(AdoException e){}
  260.             if(authors.getEOF())
  261.                 authors.moveLast();
  262.         }
  263.         else if(label.equals(buttonLabels[3]))//Last
  264.             authors.moveLast();
  265.         else
  266.             new MessageBox().show("Visual J++ 6.0 Sample","Unknown button -- command not implemented", MessageBox.ICONWARNING + MessageBox.OK);
  267.     }
  268.     /**Called when the constructor resizes the form to make room for the edits and buttons
  269.      * this code places the buttons along the bottom of the form, then removes itself as an
  270.      * event handler
  271.      */
  272.     public void form_resize(Object source, Event event)
  273.     {
  274.         //position the buttons given their number & width , the padding between them, and the margin
  275.         int buttonCount = buttonLabels.length;
  276.         int buttonMargin = (getSize().x-(buttonCount*buttonWidth + (buttonCount-1)*buttonPad))/2;
  277.         for(int i=0;i<navButtons.getSize();i++)
  278.         {
  279.             Button button = ((Button)(navButtons.getItem(i)));
  280.             button.setLocation(buttonMargin+i*(buttonWidth+buttonPad), getClientRect().height-50);
  281.             button.setSize(buttonWidth, 30);
  282.             //I need only do this once
  283.             removeOnResize(layButtons);
  284.             layButtons = null;
  285.         }
  286.     }
  287.     public void initSplash(SplashScreen splash)
  288.     {
  289.         /*the SplashScreen.gif in the project director is bigger than the default one
  290.         the default is 349*171
  291.         this one is 509*340
  292.         */
  293.         splash.initSplash(splash);
  294.         try
  295.         {
  296.             splash.setSplashPicture("SplashScreen.gif");
  297.         }
  298.         //If the file is not found, leave the default picture in place
  299.         catch(wfc.io.IOException e){}
  300.     }
  301. }
  302.