Archive for the 'J2EE' Category

Make a web site - Chapter 12 Graphical User Interface Components: Part 1

Monday, March 3rd, 2008

Chapter 12 Graphical User Interface Components: Part 1 713 LayoutManagermethod layoutContainer recalculates the layout of its Container argument. The GridLayout layout manager divides the container into a grid of rows and columns. Components are added to a GridLayout starting at the top-left cell and proceeding from left to right until the row is full. Then the process continues from left to right on the next row of the grid, and so on. Container method validate recomputes the container s layout based on the current layout manager for the Container and the current set of displayed GUI components. Panels are created with class JPanel, which inherits from class JComponent. JPanels may have components, including other panels, added to them. TERMINOLOGY .giffile name extension dispatch an event .jpgfile name extension dragging listen for an event drop-down list Abstract Windowing Toolkit event AbstractButton class event driven ActionEvent class event handler ActionListener interface event ID actionPerformed method event listener adapter class event-listener interface add method of ButtonGroup EventListenerList class add method of class Container EventObject class addItemListener method FlowLayout class addKeyListenermethod FlowLayout.CENTER addListSelectionListenermethod FlowLayout.LEFT addMouseListenermethod FlowLayout.RIGHT addMouseMotionListenermethod focus assistive technologies FocusAdapter class BorderLayout class FocusListener interface BorderLayout.CENTER Font.BOLD BorderLayout.EAST Font.ITALIC BorderLayout.NORTH Font.PLAIN BorderLayout.SOUTH getActionCommandmethod BorderLayout.WEST getClickCountmethod button getIcon method button label getKeyChar method of KeyEvent ButtonGroup class getKeyCode method of KeyEvent centered getKeyModifiersText method check box getKeyText method of KeyEvent check box label getModifiers method of InputEvent command button getPassword method of JPasswordField Component class getSelectedIndex method of JComboBox ComponentAdapter class getSelectedIndex method of JList ComponentListener interface getSelectedValuesmethod of JList Container class getSourcemethod of ActionEvent ContainerAdapter class getStateChange method of ItemEvent ContainerListener interface getText method of JLabel control getX method of MouseEvent delegation event model getY method of MouseEvent Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

712 Graphical User (Web hosting ecommerce) Interface Components: Part 1 Chapter

Sunday, March 2nd, 2008

712 Graphical User Interface Components: Part 1 Chapter 12 A MULTIPLE_INTERVAL_SELECTIONlist allows continuous range selection as described for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be selected by holding the Ctrl key while clicking each item to select. JList method setFixedCellHeight specifies the height in pixels of each item in a JList. Method setFixedCellWidth sets the width in pixels of a JList. Normally, an event generated by another GUI component (known as an external event) specifies when the multiple selections in a JList should be processed. JListmethod setListData sets the items displayed in a JList. Method getSelected- Valuesreturns the selected items as an array of Objects. Mouse events can be trapped for any GUI component that derives from java.awt.Component using MouseListeners and MouseMotionListeners. Each mouse event handling method takes as its argument a MouseEvent object containing information about the mouse event and the location where the event occurred. Methods addMouseListener and addMouseMotionListener are Component methods used to register mouse event listeners for an object of any class that extends Component. Many of the event-listener interfaces provide multiple methods. For each, there is a corresponding event-listener adapter class that provides a default implementation of every method in the interface. The programmer can extend the adapter class to inherit the default implementation of every method and simply override the method or methods needed for event handling in the program. MouseEvent method getClickCountreturns the number of mouse clicks. InputEventmethods isMetaDownand isAltDown are used to determine which mouse button the user clicked. KeyListeners handle key events that are generated when keys on the keyboard are pressed and released. A KeyListener must provide definitions for methods keyPressed, keyReleased and keyTyped, each of which receives a KeyEvent as its argument. Method keyPressed is called in response to pressing any key. Method keyTyped is called in response to pressing any key that is not an action key (i.e., an arrow key, Home, End, Page Up, Page Down, a function key, Num Lock, Print Screen, Scroll Lock, Caps Lock and Pause). Method keyReleased is called when the key is released after any keyPressedor keyTyped event. KeyEvent method getKeyCode gets the virtual key code of the key that was pressed. Class KeyEvent maintains a set of virtual key code constants that represent every key on the keyboard. KeyEventmethod getKeyText returns a String containing the name of the key that corresponds to its virtual key code argument. Method getKeyChar gets the Unicode value of the character typed. Method isActionKey determines if the key in the event was an action key. InputEvent method getModifiersdetermines if any modifier keys (such as Shift, Alt and Ctrl) were pressed when the key event occurred. KeyEventmethod getKeyModifiersText produces a string containing the names of the pressed modifier keys. Layout managers arrange GUI components on a container for presentation purposes. FlowLayout lays out components from left to right in the order in which they are added to the container. When the edge of the container is reached, components are continued on the next line. FlowLayoutmethod setAlignment changes the alignment for the FlowLayoutto Flow- Layout.LEFT, FlowLayout.CENTERor FlowLayout.RIGHT. The BorderLayoutlayout manager arranges components into five regions: North, South, East, West and Center. One component can be added to each region. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hosting web - Chapter 12 Graphical User Interface Components: Part 1

Saturday, March 1st, 2008

Chapter 12 Graphical User Interface Components: Part 1 711 Every JComponent contains an object of class EventListenerList (package javax.swing.event) called listenerListin which all registered listeners are stored. Every JComponent supports several different event types, including mouse events, key events and others. When an event occurs, the event is dispatched only to the event listeners of the appropriate type. Each event type has a corresponding event-listener interface. When an event is generated by a user interaction with a component, the component is handed a unique event ID specifying the event type. The GUI component uses the event ID to decide the type of listener to which the event should be dispatched and the event handler method to call. A JButton generates an ActionEvent when the user clicks the button with the mouse. An AbstractButton can have a rollover Iconthat is displayed when the mouse is positioned over the button. The icon changes as the mouse moves in and out of the button s area on the screen. AbstractButton method setRolloverIcon specifies the image displayed on a button when the user positions the mouse over the button. The Swing GUI components contain three state button types JToggleButton, JCheckBox and JRadioButton that have on/off or true/false values. Classes JCheckBox and JRadio- Button are subclasses of JToggleButton. When the user clicks a JCheckBox, an ItemEvent is generated that can be handled by an ItemListener. ItemListeners must define method itemStateChanged. Item- Eventmethod getStateChange determines the state of a JToggleButton. JRadioButtons are similar to JCheckBoxes in that they have two states selected and not selected (also called deselected). JRadioButtons normally appear as a group in which only one radio button can be selected at a time. The logical relationship between radio buttons is maintained by a ButtonGroupobject. The JRadioButtonconstructor supplies the label that appears to the right of the JRadioButton by default and the initial state of the JRadioButton. A true second argument indicates that the JRadioButton should appear selected when it is displayed. JRadioButtons generate ItemEvents when they are clicked. ButtonGroupmethod add associates a JRadioButtonwith a ButtonGroup. If more than one selected JRadioButton object is added to the group, the last selected JRadioButton added will be selected when the GUI is displayed. A JComboBox (sometimes called a drop-down list) provides a list of items from which the user can make a selection. JComboBoxes generate ItemEvents. A numeric index keeps track of the ordering of items in a JComboBox. The first item is added at index 0, the next item is added at index 1 and so forth. The first item added to a JComboBox appears as the currently selected item when the JComboBox is displayed. JComboBoxmethod getSelectedIndex returns the index number of the selected item. A JList displays a series of items from which the user may select one or more items. Class JList supports single- and multiple-selection lists. When an item is clicked in a JList, a ListSelectionEvent occurs. JListmethod setVisibleRowCount determines the number of items that are visible in the list. Method setSelectionMode specifies the selection mode for the list. Class JListdoes not automatically provide a scrollbar if there are more items in the list than the number of visible rows. A JScrollPane object is used to provide the automatic scrolling capability for a JList. A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items by clicking the first item, then holding the Shift key while clicking the last item to select in the range. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

710 Graphical User Interface Components: Part 1 Chapter (Web domain)

Friday, February 29th, 2008

710 Graphical User Interface Components: Part 1 Chapter 12 The original GUI components from the Abstract Windowing Toolkit package java.awt are tied directly to the local platform s graphical user interface capabilities. Swing components are lightweight components. AWT components are tied to the local platform and are called heavyweight components they must rely on the local platform s windowing system to determine their functionality and their look and feel. Several Swing GUI components are heavyweight GUI components: in particular, subclasses of java.awt.Window (such as JFrame) that display windows on the screen. Heavyweight Swing GUI components are less flexible than lightweight components. Much of each Swing GUI component s functionality is inherited from classes Component, Containerand JComponent(the superclass to most Swing components). A Container is an area where components can be placed. JLabels provide text instructions or information on a GUI. JComponent method setToolTipText specifies the tool tip that is displayed automatically when the user positions the mouse cursor over a JComponent in the GUI. Many Swing components can display images by specifying an Icon as an argument to their constructor or by using a method setIcon. Class ImageIcon (package javax.swing) supports several image formats, including Portable Network Graphics (PNG), Graphics Interchange Format (GIF) and Joint Photographic Experts Group (JPEG). Interface SwingConstants (package javax.swing) defines a set of common integer constants (such as SwingConstants.LEFT) that are used with many Swing components. By default, the text of a JComponent appears to the right of the image when the JComponent contains both text and an image. The horizontal and vertical alignments of a JLabel can be set with methods setHorizontal- Alignmentand setVerticalAlignment. Method setTextsets the text displayed on the label. Method getText retrieves the current text displayed on a label. Methods setHorizontalTextPositionand setVerticalTextPositionspecify the text position in a label. JComponent method setIcon sets the Icon displayed on a JComponent. Method get- Icon retrieves the current Icon displayed on a JComponent. GUIs generate events when the user interacts with the GUI. Information about a GUI event is stored in an object of a class that extends AWTEvent. To process an event, the programmer must register an event listener and implement one or more event handlers. The use of event listeners in event handling is known as the delegation event model the processing of an event is delegated to a particular object in the program. When an event occurs, the GUI component with which the user interacted notifies its registered listeners by calling each listener s appropriate event handling method. JTextFieldsand JPasswordFields are single-line areas in which text can be entered by the user from the keyboard or text can simply be displayed. A JPasswordField shows that a character was typed as the user enters characters, but automatically hides the characters. When the user types data into a JTextFieldor JPasswordField and presses the Enter key, an ActionEvent occurs. JTextComponent method setEditabledetermines whether the user can modify the text in a JTextComponent. JPasswordField method getPasswordreturns the password as an array of type char. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web hosting asp - Chapter 12 Graphical User Interface Components: Part 1

Thursday, February 28th, 2008

Chapter 12 Graphical User Interface Components: Part 1 709 Location - locationName : String # setLocationName( String ) : void + getLocationName( ) : String + getButton( ) : Button + getDoor( ) : Door Floor + getButton( ) : Button + getDoor( ) : Door Elevator - moving : Boolean = false -summoned : Boolean = false -currentFloor : Location -destinationFloor : Location - travelTime : Integer = 5 + ride( ) : void + requestElevator( ) : void + enterElevator( ) : void + exitElevator( ) : void + departElevator( ) : void + getButton( ) : Button + getDoor( ) : Door Fig. 12.32Modified class diagram showing generalization of superclass 12.32 Locationand subclasses Elevatorand Floor. In this section we mentioned that the goal of object-oriented ananlysis is to produce a system-requirements document. We introduced the UML use-case diagram that facilitates gathering system requirements, and we examined the two use cases in our elevator simulation. We implemented our simulator s Graphical User Interface in Java. This section concludes the discussion on the interaction between the user and the simulation model. In Thinking About Objects Section 13.17, we integrate class ElevatorControllerwith the rest of the simulation. We also introduce the UML Component diagram, which models the .class, .java, image and sound files that comprise our system. SUMMARY A graphical user interface (GUI) presents a pictorial interface to a program. A GUI (pronounced GOO-EE ) gives a program a distinctive look and feel. By providing different applications with a consistent set of intuitive user interface components, GUIs allow the user to spend more time using the program in a productive manner. GUIs are built from GUI components (sometimes called controls or widgets). A GUI component is a visual object with which the user interacts via the mouse or the keyboard. Swing GUI components are defined in package javax.swing. Swing components are written, manipulated and displayed completely in Java. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web hosting compare - 708 Graphical User Interface Components: Part 1 Chapter

Thursday, February 28th, 2008

708 Graphical User Interface Components: Part 1 Chapter 12 98 99 // other methods implementing PersonMoveListener 100 public void personCreated( 101 PersonMoveEvent event ) {} 102 103 public void personArrived( 104 PersonMoveEvent event ) {} 105 106 public void personExited( 107 PersonMoveEvent event ) {} 108 109 public void personDeparted( 110 PersonMoveEvent event ) {} 111 112 public void personPressedButton( 113 PersonMoveEvent event ) {} 114 115 } // end anonymous inner class 116 ); 117 } // end ElevatorController constructor 118 } Fig. 12.30 Class ElevatorControllerprocesses user input (part 3 of 3). Lines 53 and 71 of methods actionPerformeddisable the respective JButtons to prevent the user from creating more than one Personper Floor. Lines 78 116 of class ElevatorController declare an anonymous PersonMoveListener that registers with the ElevatorModel to reenable the JButtons. Method personEntered (lines 82 97) of the PersonMoveListener reenables the JButton associated with the Floor that the Elevator services after the Personhas entered the Elevator, the user may place another Personon the Floor. We mentioned in Section 9.23 that classes Elevatorand Floorinherited attribute capacity from superclass Location in Appendix H, we were going to use this attribute to prevent more than one Person from occupying a Location. However, the PersonMoveListener s method personEntered in class ElevatorControllerprevents the user from creating more than one Personper Floor. Therefore, we have negated the need for attribute capacityin class Location. Figure 12.32 is the modified class diagram of Fig. 9.18 removing this attribute. 1 // ElevatorConstants.java 2 // Constants used between ElevatorModel and ElevatorView 3 package com.deitel.jhtp4.elevator; 4 5 public interface ElevatorConstants { 6 7 public static final String FIRST_FLOOR_NAME = “firstFloor”; 8 public static final String SECOND_FLOOR_NAME = “secondFloor”; 9 public static final String ELEVATOR_NAME = “elevator”; 10 } Fig. 12.31 Interface ElevatorConstantsprovides Locationname constants. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 12 Graphical User Interface Components: Part 1 (Linux web host)

Wednesday, February 27th, 2008

Chapter 12 Graphical User Interface Components: Part 1 707 45 // invoked when a JButton has been pressed 46 public void actionPerformed( ActionEvent event ) 47 { 48 // place Person on first Floor 49 elevatorModel.placePersonOnFloor( 50 FIRST_FLOOR_NAME ); 51 52 // disable user input 53 firstControllerButton.setEnabled( false ); 54 } 55 } // end anonymous inner class 56 ); 57 58 // anonymous inner class registers to receive ActionEvents 59 // from second Controller JButton 60 secondControllerButton.addActionListener( 61 new ActionListener() { 62 63 // invoked when a JButton has been pressed 64 public void actionPerformed( ActionEvent event ) 65 { 66 // place Person on second Floor 67 elevatorModel.placePersonOnFloor( 68 SECOND_FLOOR_NAME ); 69 70 // disable user input 71 secondControllerButton.setEnabled( false ); 72 } 73 } // end anonymous inner class 74 ); 75 76 // anonymous inner class enables user input on Floor if 77 // Person enters Elevator on that Floor 78 elevatorModel.addPersonMoveListener( 79 new PersonMoveListener() { 80 81 // invoked when Person has entered Elevator 82 public void personEntered( 83 PersonMoveEvent event ) 84 { 85 // get Floor of departure 86 String location = 87 event.getLocation().getLocationName(); 88 89 // enable first JButton if first Floor departure 90 if ( location.equals( FIRST_FLOOR_NAME ) ) 91 firstControllerButton.setEnabled( true ); 92 93 // enable second JButton if second Floor 94 else 95 secondControllerButton.setEnabled( true ); 96 97 } // end method personEntered Fig. 12.30 Class ElevatorControllerprocesses user input (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

706 Graphical User Interface Components: Part 1 Chapter (Christian web host)

Tuesday, February 26th, 2008

706 Graphical User Interface Components: Part 1 Chapter 12 formed call the ElevatorModel s method placePersonOnFloor, which instantiates a Person object in the ElevatorModel on the specified Floor. Method placePersonOnFloor takes as an argument a String defined in interface ElevatorConstants(Fig. 12.31). This interface used by such classes as ElevatorController, ElevatorModel, Elevator, Floor and ElevatorView provides constants that specify the names of Locations in our simulation. 1 // ElevatorController.java 2 // Controller for Elevator Simulation 3 package com.deitel.jhtp4.elevator.controller; 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 // Deitel packages 13 import com.deitel.jhtp4.elevator.model.*; 14 import com.deitel.jhtp4.elevator.event.*; 15 import com.deitel.jhtp4.elevator.ElevatorConstants; 16 17 public class ElevatorController extends JPanel 18 implements ElevatorConstants { 19 20 // controller contains two JButtons 21 private JButton firstControllerButton; 22 private JButton secondControllerButton; 23 24 // reference to model 25 private ElevatorModel elevatorModel; 26 27 public ElevatorController( ElevatorModel model ) 28 { 29 elevatorModel = model; 30 setBackground( Color.white ); 31 32 // add first button to controller 33 firstControllerButton = new JButton( “First Floor” ); 34 add( firstControllerButton ); 35 36 // add second button to controller 37 secondControllerButton = new JButton( “Second Floor” ); 38 add( secondControllerButton ); 39 40 // anonymous inner class registers to receive ActionEvents 41 // from first Controller JButton 42 firstControllerButton.addActionListener( 43 new ActionListener() { 44 Fig. 12.30 Class ElevatorControllerprocesses user input (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 12 Graphical User Interface Components: Part 1 (Web server iis)

Tuesday, February 26th, 2008

Chapter 12 Graphical User Interface Components: Part 1 705 Relocate Person Elevator Person Fig. 12.29Use-case diagram from the perspective of a Person. 12.29 We must ensure that our use cases do not model interactions that are too specific between the external client and the system. For example, we do not subdivide each use case into two separate use cases such as Create Person on first Floor and Create Person on second Floor, or Relocate Person to first Floor and Relocate Person to second Floor because the functionality of such use cases is repetitive (i.e., these seemingly alternative use cases are really the same). Improper and repetitive subdivision of use cases can create problems during implementation. For example, if the designer of an automated teller machine separated its Withdraw Money use case into Withdraw Specific Amounts use cases (e.g., Withdraw $1.00, Withdraw $2.00, etc.), there could exist an enormous number of use cases for the system. This would make the implementation tedious. (Our elevator system contains only two floors separating the use case into two would not cause that much extra work; if our system contained 100 floors, however, creating 100 use cases would be unwieldy.) Constructing the Graphical User Interface Our simulation implements both the Create Person and Relocate Person use cases. We have studied the Relocate Person use case through the activity diagram of the Person in Fig. 5.29 we implement this use case and the activity diagram in Appendix H when we create class Person. We implement the Create Person use case through a graphical user interface (GUI). We implement our GUI in class ElevatorController (Fig. 12.30, line 17), which is a JPanel subclass containing two JButton objects firstControllerButton(line 21) and secondControllerButton(line 22). Each JButtoncorresponds to a Flooron which to place a Person.1 Lines 33 38 instantiate these JButtons and add them to the ElevatorController. We discuss in Section 13.17 how class ElevatorModel ties together all objects composing our elevator simulation model. Line 25 of class ElevatorController declares a reference to the ElevatorModel, because the ElevatorController allows the user to interact with the model. Lines 42 56 and 60 74 declare two anonymous ActionListener objects and register them with firstFloorController- Buttonand secondFloorControllerButton, respectively, for ActionEvents. When the user presses either JButton, lines 49 50 and 67 68 of methods actionPer 1. This approach is feasible with only two Floors. If the building had 100 Floors, we might have opted for the user to specify the desired Floorin a JTextFieldand press a JButtonto process the request. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

704 Graphical User Interface Components: Part 1 (Web hosting solutions) Chapter

Monday, February 25th, 2008

704 Graphical User Interface Components: Part 1 Chapter 12 draw and transfer funds). A person is an external entity that can play the part of a Bank- Customer. In the same manner as an object is an instance of a class, a person playing the part of a BankCustomer performing one of its roles (such as making a deposit) is an instance of actor BankCustomer. For example, when a person named Mary plays the part of a BankCustomermaking a deposit, Mary in the role of the depositor becomes an instance of actor BankCustomer. Later in that day, another person named Jon can be another instance of actor BankCustomer. In the course of a day, several hundred people might use the ATM machine some are depositors , some are withdrawers and some are transferrers, but all of these people are instances of actor BankCustomer. The problem statement in our elevator simulation supplies the actors The user requires the ability to create a person in the simulation and situate that person on a given floor. Therefore, the actor of our system is the user who controls the simulation (i.e., the user who clicks the buttons to create new Persons in the simulation). An external entity a real person plays the part of the user to control the simulation. In our system, the use case is Create Person, which encompasses creating a Person object, then placing that Personon either the first or second Floor. Figure 12.28 models one actor called User. The actor s name appears underneath the actor. The system box (i.e., the enclosing rectangle in the figure) contains the use cases for the system. Notice that the box is labeled Elevator Simulation. This title shows that this use-case model focuses on the one use case that our simulation provides to users (i.e., Create Person ). The UML models each use case as an oval. The system box for a system with multiple use cases would have one oval per use case. There is a reasonable alternate view of the use case of our elevator simulation. The problem statement from Section 2.9 mentioned that the company requested the elevator simulation to determine whether the elevator will meet the company s needs. We are designing a simulation of a real-world scenario the Personobject in the simulation represents an actual human being using an actual elevator. Thus, we may view the user of the elevator simulation as the user of the elevator. Therefore, specifying a use case from the Person object s perspective helps model how a real person uses a real elevator system. We offer the use case of Fig. 12.29, titled Relocate Person. This use case describes the Person moving (relocating) to the other Floor. (The Person travels to the second Floor if starting on the first Floor and to the first Floor if starting on the second Floor.) This use case encompasses all actions that the Personperforms along his or her journey, such as walking across a Floorto the Elevator, pressing Buttons and riding the Elevatorto the other Floor. Create Person Elevator Simulation User Fig. 12.28Use-case diagram for elevator simulation from user s perspective. 12.28 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01