[program-java] Fruit Basket

  • From: "Corbett, James" <James.Corbett@xxxxxxxxxxxxx>
  • To: <program-java@xxxxxxxxxxxxx>
  • Date: Thu, 12 Mar 2009 10:33:39 -0500

Source Code...  

...entry point...
package main;

/*
 * entry point of application 
 * this application frame work is known as 
 * MVC model view controller
 * this approach ensures encapsulation since there is only
 * one public interface
 * written by j. corbett
 * march 10, 2009
 */

public class Main {

        public static void main(String[] args) {
                new client.FruitBasketDemo();           
        }

        /*
         * the above mentioned line of code creates an instance of the 
         * FruitBasketDemo class with out creating an object.
         * this is possible because there will be no further 
         * reference to any object if declared. 
         * an import is not required because class FruitBasketDemo is 
implicitly declared by prefixing the class name with the package name
         * i.e. client.FruitBasketDemo.   
         */

} // end of class


************


package client;

/*
 * The specifications for a fruit basket program are as follows:  
 *1. The program is a GUI interface, or the equivalent with at least an edit 
box, list box, and two buttons.  
 *2. The user can type the name of a fruit, e.g., apple, in the edit box.  
 *3. When the Add button is activated, the fruit is copied into the list box 
and the edit box is cleared to be ready for another entry.  
 *4. When the Delete button is activated, the currently focused fruit in the 
list box, or basket, is removed.
 *5. For accessibility, static labels should be associated with the edit box 
and list box, since these controls do not have captions like buttons.  
 *6. Keyboard users will also appreciate a unique hot key for each control.  
 *7. Making Add the default button allows a fruit to be added by simply 
pressing Enter after typing its name.  
 *8. An error message alerts the user if Add is pressed without a fruit in the 
edit box or Delete is pressed without a fruit in the list box.
 *written by j. corbett
 *march 10, 2009
 */

//required libraries for this example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.*;

public class FruitBasketDemo {

        private Display display;
        private Shell shell;
        /*
         * the following items are private members of this class
         * all items are controls also known as widgets.
         * they are declared private so as the outside world is not aware of 
them
         * however declaring them at this point of the application
         * will make them accessible to the entire class
         * regardless of where the instance is created.
         */

        private Combo cFruit;
        private Text tFruit;
        private Button cmdAdd;
        private Button cmdDelete;
        private Button cmdExit;
        private MessageBox msg;

        public FruitBasketDemo() {

                display = new Display(); // new instance of display
                shell = new Shell(display); // new instance of shell with 
display passed as a parameter

                msg = new MessageBox(shell); // new instance of the message box 
widget

                run(); // call to the run method

        } // end of constructor method

        private void run() {

                shell.setSize(450, 300);

//              centers shell on screen

                Monitor primary = display.getPrimaryMonitor ();
                Rectangle bounds = primary.getBounds ();
                Rectangle rect = shell.getBounds ();
                int x = bounds.x + (bounds.width - rect.width) / 2;
                int y = bounds.y + (bounds.height - rect.height) / 2;
                shell.setLocation (x, y);

//              end of centering

//              setting font size and style for screen caption 

                FontData largFont = new FontData("Times New Roman",24,SWT.BOLD);
                shell.setFont(new Font(display, largFont));
                shell.setText("Fruit Basket Demo using JAVA and SWT");

                // end of setting font

                registerShellEscapeListener();

                //a group is a container

                Group grp = new Group(shell, SWT.NONE); // new instance of the 
group widget
                grp.setSize(400, 200);
                grp.setLocation(15, 25);
                grp.setText("");

                // end of group in this context, however all widgets are now 
part of the group

                Label label1 = new Label(grp, SWT.FLAT); // new instance of the 
label widget
                label1.setSize(75, 20);
                label1.setLocation(20, 20);
                label1.setText("Select a Fruit");

                cFruit = new Combo(grp, SWT.DROP_DOWN|SWT.READ_ONLY); // new 
instance of the combo widget
                cFruit.setSize(100, 20);
                cFruit.setLocation(100, 20);

                Label label2 = new Label(grp, SWT.FLAT); // new instance of the 
label widget
                label2.setSize(50, 20);
                label2.setLocation(220, 20);
                label2.setText("Enter Fruit");

                tFruit = new Text(grp, SWT.BORDER); // new instance of the text 
widget
                tFruit.setSize(100, 20);
                tFruit.setLocation(280, 20);

                registerTextListener();

                cmdAdd = new Button(grp, SWT.PUSH); // new instance of the 
button widget
                cmdAdd.setSize(60, 20);
                cmdAdd.setLocation(90, 80);
                cmdAdd.setText("&Add");

                cmdDelete = new Button(grp, SWT.PUSH);
                cmdDelete.setSize(60, 20);
                cmdDelete.setLocation(180, 80);
                cmdDelete.setText("&Delete");

                cmdExit = new Button(grp, SWT.PUSH);
                cmdExit.setSize(60, 20);
                cmdExit.setLocation(270, 80);
                cmdExit.setText("E&xit");

                registerCommandButtonListeners();

                shell.open();

                while (!this.shell.isDisposed()) {
                        if (!this.display.readAndDispatch()) {
                                this.display.sleep();
                        }
                }

        } // end of run

        /*
         * the following method listens for the escape button to be pressed
         * and then executes the code.... in this case it closes the shell
         */

        private void registerShellEscapeListener() {

                shell.addListener (SWT.Traverse, new Listener () {
                        public void handleEvent (Event event) {
                                switch (event.detail) {
                                case SWT.TRAVERSE_ESCAPE:
                                        shell.close ();
                                        event.detail = SWT.TRAVERSE_NONE;
                                        event.doit = false;
                                        break;
                                }
                        }
                });

        } // end of register shell escape listener

        /*
         * widgets require listeners to determine the event being triggered at 
a particular time.
         * In the following listener method, the listener for the 
         * text box is waiting for the enter key to be pressed on the text 
widget.
         * When ever the event is triggered, control is passed to the method 
and code specific to the 
         * event is executed.
         */

        private void registerTextListener() {

                tFruit.addTraverseListener(new TraverseListener () {
                        public void keyTraversed(TraverseEvent e) {
                                switch (e.detail) {
                                case SWT.TRAVERSE_RETURN:                       
                        
                                        setFruitAdded();
                                }
                        }
                });

        } // end of register text listener

        private void registerCommandButtonListeners() {

                cmdAdd.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                                setFruitAdded();
                        }
                });

                cmdDelete.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                                setFruitDeleted();
                        }
                });

                cmdExit.addSelectionListener(new SelectionAdapter() {
                        public void widgetSelected(SelectionEvent e) {
                                shell.close();
                        }
                });

        } // end of command button listeners

        private void setFruitAdded() {

                if (tFruit.getText().equals("")) {
                        msg.setText("Caution");
                        msg.setMessage("You cannot leave the edit field empty, 
please try again!");
                        msg.open();
                        tFruit.setFocus();
                        return;
                } else {
                        cFruit.add(tFruit.getText());
                        cFruit.setFocus();
                        cFruit.select(0);
                        tFruit.setText("");
                }

        } // end of set fruit added

        private void setFruitDeleted() {

                if (cFruit.getItemCount() == 0) {
                        msg.setText("Caution");
                        msg.setMessage("You cannot delete an item from the 
fruit basket, because there is nothing in the basket!");
                        msg.open();
                        cFruit.setFocus();
                        return;
                } else {
                        cFruit.remove(cFruit.getSelectionIndex());

                        if (cFruit.getItemCount() > 0) {
                                cFruit.select(0);
                        }

                        cFruit.setFocus();      
                }

        } // end of set fruit deleted

} // end of class 

James M. Corbett

A / Technical Specialist
GST/HST Micros | Micros de la TPS/TVH
GST/HST Redesign Division | Division de la restructuration de la TPS/TVH 
Revenue and Accounting Systems Directorate (RASD) | Direction des Systèmes de 
revenu et de comptabilité (DSRC)
Information Technology Branch (ITB) | Direction générale de l'informatique (DGI)
Canada Revenue Agency | Agence du revenue du Canada

(613) 941-1338

"...Is a hippopotamus a hippopotamus, or just a really cool Opotamus?" 

Other related posts:

  • » [program-java] Fruit Basket - Corbett, James