Step 10.9: Running the Inquire class


Step 10.9: Running the Inquire class

click to expand

Run the class from the Run menu of the Eclipse main menu bar.

q 10.9(a) Select the Inquire class by left-clicking on it.

q 10.9(b) From the main menu bar, select Run/Run As/Java Application.

click to expand
Figure 10.46: Running Inquire as a Java Application.

This will create a launch configuration for Inquire with the default characteristics and then attempt to run it.

This is the result of the application. The application is functionally the same as the one you created in Step 9. You can enter various values in the Item Number field and click the Find button to see if the value you entered is valid. If it is, you will see a description (the valid item numbers are CAT, DOG, and OCTOPUS).

If you enter an invalid item number, the program will highlight the field as well as returning a value of "Not Found". You can run this as many times as you like. Click the Exit button when you want the application to end.

Congratulations! You have successfully used Eclipse to create and run a Java application incorporating both SWT and JDBC. This is quite an accomplishment.

I hope this book has given you enough insight into the various technologies to continue researching them on your own. Good luck!

For those of you who would care to, I've included a final section reviewing the code for this application. There's really very little changed from the Prompt application in Step 9, and much of what has changed has been covered already in my review of HelloSQL, but it may still be helpful to review the final product.

Code review: Inquire

Most of the code in this method you've seen already, either in the Prompt code (from Step 9) or the HelloSQL application earlier in this step. Since that's the case, I'm only going to highlight and review those lines that you haven't seen before.

 import java.sql.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class Inquire {        // Database constants        private static final String sqlClass = "org.hsqldb.jdbcDriver";        private static final String sqlUrl   = "jdbc:hsqldb:hsqldb";        private static final String sqlUser  = "sa";        private static final String sqlPwd   = "" ;    // Database resources    private Connection c;    private Statement s;    // Resources    private Display display;    private Shell shell;    private Color red, white;    // Fields    private Text f1;    private Label f2;    public Inquire() {    }    public void run() {           try {                 init();                 setLayout();                 createWidgets();                 show();                 cleanup();           }           catch (Exception e)           {                 System.out.println("Error: " + e);           }    } 

This is the interesting effect of exceptions. Because some of the lower-level methods now throw exceptions (because they invoke JDBC functions), this high level method must incorporate a try/catch block.

 private void init()        throws Exception {        // Open the database        Class.forName (sqlClass);        c = DriverManager.getConnection(sqlUrl, sqlUser, sqlPwd);        s = c.createStatement() ;        // Create a standard window        display = new Display();        shell = new Shell(display);        shell.setText("Inquire");        // Create some colors        red = new Color(display, 255, 0, 0);        white = new Color(display, 255, 255, 255); } 

This is the other effect of exceptions. Rather than embedding the try/catch in this method, I simply specified a throws clause in the method definition. This will "bubble up" any exceptions to the caller.

 private void setLayout() {        // Create the layout for the widgets        GridLayout grid = new GridLayout();        grid.numColumns = 2;        grid.makeColumnsEqualWidth = true;        shell.set Layout (grid); } private void createWidgets() {        // Create my widgets        Label l1 = new Label(shell, SWT.NONE);        l1.setText("Item Number:");        f1 = new Text(shell, SWT.BORDER  SWT.SINGLE);        f1.setTextLimit(20);        Label 12 = new Label(shell, SWT.NONE);        l2.setText("Description:");        f2 = new Label(shell, SWT.NONE);        f2.setText(" ";        Button bl = new Button(shell, SWT.PUSH);        b1.setText("Find");        b1.addListener(SWT.Selection, new Listener() {           public void handleEvent(Event event) {                  doFind();           }        });        Button b2 = new Button(shell, SWT.PUSH);        b2.setText("Exit");        b2.addListener(SWT.Selection, new Listener() {           public void handleEvent(Event event) {                  doExit();           }        }); } private void doFind() {        try {              String desc = getDescription(f1.getText());              if (desc == null)              {                 f1.setForeground(white);                 f1.setBackground(red);                 f2.setText("Not Found");                 f2.setForeground(red);            }            else            {                 f1.setForeground(null);                 f1.setBackground(null);                 f2.setText(desc);                 f2.setForeground(null);            }      } catch (Exception e) {                   f1.setForeground(white);                   f1.setBackground(red);                   f2.setText("Error: " + e);                   f2.setForeground(red);      } } 

The doFind method isn't affected too much, except that it must now take exceptions into account. Since the application uses the f2 field to display the "Not Found" message, it made sense to use the same convention to show exception messages.

 private void doExit() {        shell.close(); } private String getDescription(String item)        throws Exception {        String description = null;        String query = "SELECT * FROM ITEMS WHERE ItemNumber=' " + item + "'";        ResultSet rs = s.executeQuery(query);        if (rs.next()) description = rs.getString("Description");        return description; } 

The getDescription method is the method most affected by the switch to JDBC. Instead of a hardcoded hash table and a lookup, you must query the database. I'm using the most primitive version of the syntax here: I just format the SELECT statement on the fly. For any but the simplest of queries, this can get very messy, especially when trying to quote strings properly. Instead, you might want to consider a prepared statement (the syntax if which is not covered in this particular manual).

 private void show() {         // Final setup - size the display show it         shell.setSize(200, 100);         shell.open();         while (!shell.isDisposed()) {                if (!display.readAndDispatch())                       display.sleep();         }     }     private void cleanup()            throws Exception     {         // When done, clean up resources         display.dispose();         red.dispose();         white.dispose();         // Shut down database         s.close();         c. close();     }     public static void main(String[] args) {        new Inquire().run() ;        System.exit(0);     } } 

The only change left is the addition of the throws clause to the cleanup method definition. I'll leave determining the cause for this change as a final exercise for you, my stalwart reader.

I hope you've enjoyed reading this book as much as I've enjoyed writing it!




Eclipse
Eclipse: Step by Step (Step-by-Step series)
ISBN: 1583470441
EAN: 2147483647
Year: 2003
Pages: 90
Authors: Joe Pluta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net