Step 9.9: Running the Prompt class


Step 9.9: Running the Prompt class

click to expand

q 9.9(a) Select the Prompt class by left-clicking on it.

q 9.9(b) From the Run tool dropdown, select Run As/Java Application.

click to expand
Figure 9.65: Running Prompt as a Java Application.

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

However, you'll run into the same problem you did with HelloSWT: The JVM won't be able to find the native implementation, as shown in Figure 9.66.

click to expand
Figure 9.66: Red text once again indicates that you've got a problem.

q 9.9(c) Expand the error.

click to expand
Figure 9.67: Expand the error by double-clicking on the Console view's title bar.

You'll see the error as shown in Figure 9.68.

click to expand
Figure 9.68: Another UnsatisfiedLinkError ”in fact, the same one as in Step 9.6.

q 9.9(d) Restore the error to normal size .

click to expand
Figure 9.69: Restore the error to normal size by double-clicking on its title bar again.

Now you'll see the workbench as in Figure 9.70 ”back to normal size for the error, but an error still exists.

click to expand
Figure 9.70: Back to normal size for the error.

You could just go in and change the launch configuration as you did with HelloSWT. This is a valid method, and it's the technique you should use for new library files until they are tested . However, I want to show you a different technique that you should use once you're comfortable that the library works.

Once again you'll use the command prompt.

q 9.9(e) Start a Windows command line and execute the following commands.

You'll be using the value for $LIBPATH that you wrote down in Step 9.6(i).

 Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\>echo %PATH% C:\WINNT;C:\WINNT\System32;C:\WINNT\System32\Wbem C:\>copy "c:\Program Files\eclipse\plugins\org.eclipse.swt.win32_2.1.0\os\win32\*" c:\WINNT c:\Program Files\eclipse\plugins\org.eclipse.swt.win32_2.1.0\os\win32\x86\swt-win32-2133.dll     1 file(s) copied. 
  1. echo %PATH%

    This will show you your path. You should see "C:\WINNT" in the path. If not, you have a very nonstandard Windows configuration, and I assume you're an expert and can modify the next step as appropriate.

  2. copy "c:\Program

    Files\eclipse\plugins\org.eclipse.swt.win32_2.1.0\os\win32\x86\*" c:\WINNT

    The format of this line is

    copy "$LIBPATH\*" C:\WINNT

    This line copies the SWT native library from its Eclipse library into your system's library path. This will allow the system to find it. As I mentioned at the beginning of this step, the folder name is the $LIBPATH value you saved in Step 9.6(i).

Note  

Each time you upgrade Eclipse, you may have to repeat this step. If there are changes to the native libraries, the Eclipse team renames the library and changes all references to the new name. To see if this is necessary, try to run one of your simple SWT example applications. If you get the UnsatisfiedLinkError, you'll need to repeat this step.

Now go back and rerun the application.

q 9.9(f) Using the Run tool, re-run Prompt.

click to expand
Figure 9.71: Running the application again.

This time you will get very different results, as shown on the next page.

This is the result of the application. 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. Select the Exit button when you want the application to end.

At this point, you can either finish up this step by reading the review of the code in the following pages, or you can just skip directly to the next step, Step 10, where you will attach a database to this program.

Code review: Prompt

Prompt is a simple application that is meant only to show a few things: how to use a layout in a window, how to add components to a layout, how to interact with components via listeners, and finally how to change the appearance of components . You'll also be introduced to a couple of simple concepts, such as resource disposal.

 import java.util.Hashtable; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; 

The java.util.Hashtable import is hopefully self-explanatory, and the others are all standard imports in just about any SWT application.

  • org eclipse.swt allows the use of the various SWT constants.

  • org eclipse.swt.graphics allows the use of the Color class.

  • org eclipse.swt.layout allows the use of the SWT layouts.

  • org eclipse.swt.widgets defines most components and the like.

 public class Prompt { 

Prompt is a public class. Nothing special here.

 // Resources   Display display;   Shell shell;   Color red, white;   // Fields   Text f1;   Label f2; 

Here are some global resources for the class. I define the application resources (the Display, Shell and Color, most of which must be disposed of), as well as the application widgets f1 and f2-the ones that must be changed during the application. These are the fields whose attributes change in response to user input.

 public Prompt() {   } 

The constructor is very simple. I prefer to do a lazy initialization at run time.

 public void run() {          init();          setLayout();          createWidgets();          show();          cleanup();   } 

This is the primary execution flow. The run method is invoked from main, and it executes individual subprocedures. Each subprocedure has its own specific tasks :

  • init creates the Display and Shell objects as well as any global resources.

  • setLayout applies the appropriate layout object to the window.

  • createWidgets creates the actual user interface widgets such as buttons and fields, including associating the listeners.

  • show executes the dispatch loop.

  • cleanup disposes of all resources.

     private void init() {          // Create a standard window          display = new Display();          shell = new Shell(display);          shell.setText("Prompt3");          // Create some colors          red = new Color(display, 255, 0, 0);          white = new Color(display, 255, 255, 255);   } 

The init method is used to create the Display and Shell objects for the primary window, as well as create the Color objects that are used in other methods .

 private void setLayout() {          // Create the layout for the widgets          GridLayout grid = new GridLayout();          grid.numColumns = 2;          grid.makeColumnsEqualWidth = true;          shell.setLayout(grid);   } 

The setLayout method creates a GridLayout object with two columns . Each row in the layout holds exactly two widgets. The first two rows contain a label and a field, and the last row contains two buttons. For more complex windows, you can nest grids inside one another or use other layout classes.

The createWidgets method is the most complex method. It creates each of the individual user interface (UI) components, and for some of them it adds listeners.

 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 l2 = new Label(shell, SWT.NONE);          l2.setText("Description:");          f2 = new Label(shell, SWT.NONE);          f2.setText(" "); 

These are the simple UI components, the labels and fields. The user interacts with them to a small degree, but the application doesn't really handle individual events for these fields. It lets the system handle the events.

 Button b1 = 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() ;             }      }); } 

Buttons, on the other hand, usually require application attention. They are the way the user tells the application to do something. In this case, each button is attached to a Listener object. Listeners are special objects designed to handle events. In this very simple design, each listener simply passes the event directly to another method. I use this convention often, where the name of the method is "do" followed by the button name. In this application, the two buttons are Find and Exit, so the two button listener methods are doFind and doExit.

 private void doFind() {          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);          }   } 

The doFind method is actually the only "business logic" in the application. It passes the item number entered by the user, (f1.getText()), to the getDescription method. If a null value is returned, then the item number was not found, and the appropriate error actions are taken: The description is set to not found, and both the input field and description are changed to a red background or foreground to indicate an error condition. Otherwise the value is assumed to be good, and the fields are set back to their default colors.

 private void doExit() {          shell.close();   } 

The doExit method is one of the simplest methods. It only has to invoke the close method of the shell object, which will in turn cause the event loop to end.

 private static final Hashtable items;   static {         items = new Hashtable();         items.put("DOG", "My Puppy");         items.put("CAT", "My Kitty");         items.put("OCTOPUS", "Calamari Kid");   } 

This is a special static variable that has its own static initializer. The first time this class is accessed, this routine is invoked and the Hashtable named items is filled with a few hardcoded values.

 private String getDescription(String item)   {          return (String) items.get(item);   } 

This method simulates a database inquiry by looking for the item number passed into it in the items table.

 private void show() {          // Final setup - size the display show it          shell.setSize(200, 100);          shell.open();          while (!shell.isDisposed()) {                if (!display.readAndDispatch())                      display.sleep();          }   } 

The show method is pretty standard (except maybe for hardcoding the size of the window). Basically, it just opens the window then begins the event-dispatching loop. When the window is closed, the method returns.

 private void cleanup() {          // When done, clean up resources          display.dispose();          red.dispose() ;          white.dispose() ;   } 

This method is invoked at the end of the application, and it is used to dispose of any resources that were allocated during the application. This should be a standard method for any application that allocates resources.

 public static void main(String[] args) {         new Prompt().run() ;         System.exit(0);   } } 

This is a slight twist on the old main method. In this case, the main method does nothing more than create a new Prompt object and execute its run method. Upon completion, the main method then exits. This is a very clean programming style.




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