Chapter 18 Building the user interface This chapter

Chapter 18 Building the user interface

This chapter discusses n n Java’s graphical user interface. Swing: an enhancement of a library called the Abstract Window Toolkit (AWT). Event-driven, window-based applications. Swing as a case study of how large libraries are organized.

The system interface n n n The interface and the model are two of the principal components of a software system. The interface handles interaction with the external world. When the external world is a person, the interface is called a user interface.

Algorithm-driven interfaces n n n In an algorithm-driven approach, the application determines exactly what information it needs from the environment, and when it needs it. The application has access to several streams of data. A stream is a sequence of bytes.

Algorithm-driven interfaces (cont. ) n n A character stream is a set of ASCII characters. Otherwise it is a binary stream. Input stream sources can be a user’s keyboard, a file, another program, an external device, etc. Output stream targets can be a user’s display screen, a file, another program, an external device, etc.

Java compiler stream n n 1 input stream 2 output streams

Nim game user interface Enter number of Sticks. 3 Player 1 takes 2 leaving 1 sticks. Player 2 takes 1 leaving 0 sticks. Game over. Player 1 won. To Play again, enter 1; to stop enter 0 1 Enter number of sticks. n This game writes output and reads input.

Filters n n Where input data comes from and where output data goes often is not important to the application. Filters read input from a single stream called standard input, write output to an output stream called standard output, and write error messages to a stream called standard error.

Event-driven interfaces n n n The application is “active” in an algorithm -driven interface; it is “passive” in an event-driven system. An event-driven system waits for something to happen (an event) in the environment. event-driven: an input-output model in which the application waits for an event to occur, responds to the event, and waits for the next event.

Event-driven interfaces (cont. ) n An application with a window-based interface provides a graphical “control panel” containing a range of options.

Event-driven interfaces (cont. ) n n In a window-based system, we assume that there is a native windowing system that actually detects events like mouse clicks, mouse movement, key strokes, etc. , and manages the display. Java applications interact with the native windowing system.

Swing n A graphical user interface is made up of components (widgets). windows u buttons u menus, etc. u n n Each components has attributes of location, size, shape, color, etc. Components are defined in a class library contained in the package javax. swing

Key Components of a GUI Application

Inheritance Hierarchy for Java GUI Components


JComponent abstract class

JComponent abstract class (cont. )

JComponent abstract class (cont. ) n JComponent is a subclass of the AWT. public Color get. Foreground (); Color get. Background (); Point get. Location (); Dimension get. Size (); public void Color set. Foreground(Color fg); Color set. Background(Color bg); Point set. Location(Point p); Dimension set. Size(Dimension d; )

JComponent abstract class (cont. ) n Many of the methods are overloaded. For instance, there are versions of set. Location and set. Size that take two int arguments rather than a Point or Dimension.

JComponent abstract class (cont. ) n n Color, Point, and Dimension are AWT classes. Instances of Color are immutable. The class Color defines a number of constant references. i. e. Color. red Class Dimension encapsulates width and height.

Containers n n Objects that contain components are containers. JComponent is a subclass of Container. component: a distinct element of a graphical user interface, such as a button, text field, etc. container: a graphical user interface component that can contain other components.

Containers (cont. )

JPanel n Used as a place to put a collection of other components. Jpanel p = new Jpanel(); p. add(new Jbutton(“on”)); p. add(new Jbutton(“off”));

Manipulating content n Class Container defines an extensive set of methods for manipulating its content. public int get. Component. Count() The number of Components in this Container. public Component get. Component (int n) The Component with the specified index. require: 0 <= n < this. get. Component. Count() public void remove (Component comp) Remove the specified Component. public void remove (int index); Remove the Component with the specified index. require: 0 <= index < this. get. Component. Count()

Top-level containers n A top-level container is one that is not contained in any other container. i. e. JApplet, JDialog, JFrame, and JWindow.

JFrame n n n A window with a title and a border. JFrame is a subclass of java. awt. Container, not JComponent. It delegates the responsibility of managing its components to another object--JRoot. Pane.

JRoot. Pane n n JRoot. Pane is a JComponent whose principal responsibility is to manage the content of some other container. It is a composite object, including a content pane. The content pane is usually a JPanel, and is the working area of the JFrame, excluding title, border, menu. Components are not added directly to the JFrame, but to the content pane.

JRoot. Pane (cont. ) n get. Content. Pane returns a Container. JFrame f = new JFrame(“A Frame”); JButton b = new JButton(“Press”); Container cp = f. get. Content. Pane(); cp. add(b); n JApplet, JDialog, JWindow and JInternal. Frame also use JRoot. Pane to manage components.


GUI Design Pattern Application Variables n Declare as application variables the GUI components and any data that will be accessed by event handlers, utility methods, and inner classes. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Dice Class Variables class Dice. Toss extends JFrame { // application variables private JPanel panel. A, panel. B; private JLabel die. Label 1, die. Label 2, total. Label; private JText. Field total. Field; private JText. Area total. Area; private JButton toss. Button; private Dice d = Dice. get. Dice(); private Image. Icon[] die. Pict = {null, new Image. Icon("die 1. gif"), new Image. Icon("die 2. gif"), new Image. Icon("die 3. gif"), new Image. Icon("die 4. gif"), new Image. Icon("die 5. gif"), new Image. Icon("die 6. gif")}; . . . © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved. }

GUI Application Constructor n Initializes frame properties and loads the components. u Set u title with set. Title(title. Str). set. Bounds(pos. X, pos. Y, width, height) sets the size of the frame and its position on the screen. u set. Default. Close. Operation(JFrame. EXIT_ closes the frame and exits the application when the user clicks the close box in the frame. ON_CLOSE) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

GUI Application Constructor (concluded) n n Components in a frame reside in a region called the content pane. Use get. Content. Pane() to access the content pane and assign it to a Container reference variable. Container content = get. Content. Pane(); n Create and organize components and add them to the content pane. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Dice. Toss Constructor public Dice. Toss() {. . . // establish the content pane for the window Container content = get. Content. Pane(); content. set. Layout(new Border. Layout()); // panel and labels for the two die pictures JPanel panel. A = new JPanel(); die. Label 1 = new JLabel(); die. Label 2 = new JLabel(); panel. A. add(die. Label 1); panel. A. add(die. Label 2); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved. // text area to store results of

Dice. Toss Constructor (continued) // panel with toss button, total label, // and text field for the total // the toss button has an action listener // (see next section) JPanel panel. B = new JPanel(); toss. Button = new JButton("Toss"); toss. Button. add. Action. Listener(new Toss. Event()) total. Label = new JLabel("Total"); total. Field = new JText. Field(4); panel. B. add(toss. Button); panel. B. add(total. Label); panel. B. add(total. Field); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Dice. Toss Constructor (concluded) // add panels and individual components to th // content pane using compass point constants // for class Border. Layout. // the text area is embedded in a JScroll. Pane // to add scroll bars content. add(panel. A, Border. Layout. NORTH); content. add(new JScroll. Pane(total. Area), Border. Layout. CENTER); content. add(panel. B, Border. Layout. SOUTH); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Peers n n n JApplet, JDialog, JFrame, JWindow are heavyweight components. Instances of subclasses of JComponent are lightweight components. When a heavyweight component is created, the AWT also creates an associated native GUI component called a “peer. ” i. e. Creation of JFrame, also creates a “frame peer. ”

Peers (cont. ) n n n Peers actually do the work of capturing user input and managing the screen area in which the component is displayed. Lightweights are implemented completely by Java. Lightweights are drawn on the space provided by their heavyweight parent containers.

Top-level frame import javax. swing. *; public class Display. Frame { public static void main (String[] args){ JFrame f = new JFrame (“A Frame”); f. set. Size(300, 200); f. set. Visible(true); } }

Adding components n n n Adding components to the frame won’t cause the component to appear suddenly on the display. A Layout. Manager is an object responsible for positioning and sizing the components in a container. A Layout. Manager is specified in the interface java. awt. Layout. Manager. public Layout. Manager get. Layout(); public void set. Layout (Layout. Manager manager);

Layout. Manager implementations n n n n Flow. Layout: left to right, top to bottom. Border. Layout: “north”, “south”, “east”, “west”, “center. ” Grid. Layout: two-dimensional grid. Card. Layout: one at a time from a “deck” Grid. Bag. Layout: vertically and horizontally according to constraints. Box. Layout: either a single horizontal row or single vertical column. Overlay. Layout: specified components align in the same place; components are laid out on top of each other.

Flow. Layout


Border. Layout


Grid. Layout

n When the Grid. Layout is created, we specify that we want a grid of 3 rows and 2 columns. Since there is more than 6 components, Grid. Layout expands the number of columns, while keeping the number of rows at 3.

Container validity n n n A Container is valid if it does not need to be laid out. i. e. size is known to the system, and the layout manager knows about all its components. A Container is invalid if its state is inconsistent with its appearance. A Container to which a component has been added after it was last laid out is invalid.

Container validity (cont. ) n Any number of things can cause the layout manager to lay out the Container. u validate explicitly sets the Container’s valid property to true, and instructs the layout manager to lay out the Container. u is. Valid returns the value of this property. public boolean is. Valid(); public void validate();

Capturing and handling events n n n event: the occurrence of an action, typically external to the system, that the system is aware of and must respond to. low-level events: pressing or releasing a key, moving the mouse, pressing a mouse button. high-level events: selecting an item on the menu, pressing a button, entering text in a field. u High-level events usually involve one or more low-level events.

Some high-level events key event: a keyboard key pressed or n n n released. mouse event: the mouse is moved or dragged, a button pressed or released, the mouse cursor enters or exits component event: a component is hidden, shown, resized, or moved. container event: a component is added to or removed from a container. window event: a window is opened, closed, iconified, de-iconified, activated, deactivated.

Some high-level events (cont. ) n n n focus event: a component gains or loses focus. action event: a high-level event occurs. adjustment event: a high-level event occurs representing scrollbar motions. item event: a high-level event occurs when user selects a checkbox, choice, or list item. document event: a Text. Component’s content changes.

Java event classes

Java event classes (cont. ) n The source of an event is determined with: public Object get. Source(); n n n An object that monitors when an event occurs is called a listener. To be notified of an event, a listener must register with the event’s source. The relation between a listener and an event source is the observes relation.

Example import java. awt. *; import javax. swing. *; import java. awt. event. *; public class On. Off. Test { public static void main (String[] args){ On. Off. Switch sw = new On. Off. Switch(); } } class On. Off. Switch extends JFrame { public On. Off. Switch() { super(“On/Off Switch”); JButton button= new JButton(“On/Off”); Container cp = this. get. Content. Pane(); button. set. Forground(Color. black); button. set. Background(Color. white); cp. add(button, Border. Layout. Center); this. set. Size(300, 200); this. set. Visible(true); } }

Example

Event. Listener classes

Adding a listener n There is only one method specified in the interface Action. Listener. public void action. Performed(Action. Event e); class Switcher implements Action. Listener { public void action. Performed (Action. Event e) {…} } n When the user presses the button, an Action. Event is generated.

Example class On. Off. Switch extends JFrame { public On. Off. Switch() { super(“On/Off Switch”); JButton button= new JButton(“On/Off”); Switcher control = new Switcher(); button. add. Action. Listener(control); Container cp = this. get. Content. Pane(); button. set. Forground(Color. black); button. set. Background(Color. white); cp. add(button, Border. Layout. Center); this. set. Size(300, 200); this. set. Visible(true); } }

Example (cont. ) public void action. Performed(Action. Event e){ Component source = (Component)e. get. Source(); Color old. Foreground = source. get. Foregound(); source. set. Foreground (source. get. Background()); source. set. Background(old. Foreground); }

Example (cont. )

Example (cont. ) n Since the listener explicitly determines the source of the event, it could handle events from several sources without modification. class On. Off. Switch extends JFrame { public On. Off. Switch() { super(“On/Off Switch”); JButton button 1= new JButton(“On/Off”); JButton button 2= new JButton(“On/Off”); Switcher control = new Switcher(); button 1. add. Action. Listener(control); button 2. add. Action. Listener(control); … } }

Adding a window listener n n n We would like to terminate the application when the user selects the “Close” option from the top-level window menu. Selecting “Close” generates a Window. Event in the JFrame, specifically a “window closing” event. The Window. Listener interface is a bit more complicated than the Action. Listener interface; it specifies seven methods.

Adding a window listener (cont. ) void window. Activiated (Window. Event e) Invoked when window becomes the active window. void window. Closed (Window. Event e) Invoked when window has been closed. void window. Closing (Window. Event e) Invoked when user attempts to close window. void window. Deactiviated (Window. Event e) Invoked when window becomes no-longer-active window. void window. Deiconified (Window. Event e) Invoked when window changes from minimized to normal. void window. Iconified (Window. Event e) Invoked when window changes from normal to minimized. void window. Opened (Window. Event e) Invoked when window is first made visible.

Adding a window listener (cont. ) n To simplify the implementation, Java provides “event adapter” classes. class Terminator extends Window. Adapter { public void window. Closing(Window. Event e) { Window w = e. get. Window(); w. dispose(); } public void window. Closed(Window. Event e) { System. exit(0); } }

Adding a window listener (cont. ) n We must create a Terminator instance and register it with the top-level JFrame. public On. Off. Switch() { super(“On/Off Switch”); JButton button= new JButton(“On/Off”); Switcher control = new Switcher(); Terminator arnold = new Terminator(); button. add. Action. Listener(control); this. add. Window. Listener(arnold); … }

Adding a window listener (cont. ) n Terminator is an ideal candidate for being made an anonymous inner class. this. add. Window. Listener( new Window. Adapter() { public void window. Closing(Window. Event e) { e. get. Window(). dispose(); } public void window. Closed(Window. Event e) { System. exit(0); } } );


Some class features

Component n Background color: public Color get. Background() public void set. Background(Color c) n Foreground color: public Color get. Foreground() public void set. Foreground(Color c) n Location: public Point get. Location() public void set. Location(int x, int y) public void set. Location(Point p) n Location on screen: public Point get. Location. On. Screen() n Size: public Dimension get. Size() public void set. Size(int height, int width) public void set. Size(Dimension d)

Component (cont. ) n Preferred size: public Dimension get. Preferred. Size() n Minimum size: public Dimension get. Minimum. Size() n Parent: public Container get. Parent() n Enable: public boolean is. Enabled() public void set. Enabled(boolean enabled) n Valid: public boolean is. Valid() public void validate() public void invalidate()

Component (cont. ) n Visible and Showing: public boolean is. Visible() public boolean is. Showing() public void set. Visible(boolean visible) n Font: public Font get. Font() public void set. Font(Font f) n Graphics: public Graphics get. Graphics() n Listeners: public void add. Component. Listener( Component. Listener listener) public void remove. Component. Listener( Component. Listener listener)

Component (cont. ) n Listeners (cont. ): public void add. Focus. Listener( Focus. Listener listener) public void remove. Focus. Listener( Focus. Listener listener) public void add. Key. Listener( Key. Listener listener) public void remove. Key. Listener( Key. Listener listener) public void add. Mouse. Listener( Mouse. Listener listener) public void remove. Mouse. Listener( Mouse. Listener listener) public void add. Mouse. Listener( Mouse. Motion. Listener listener) public void remove. Mouse. Listener( Mouse. Motion. Listener listener)

Containers n Component Manipulation: public int get. Component. Count() public Component get. Component(int position) public Component get. Component. At(int x, int y) public Component get. Component(Point p) n Component Manipulation (cont. ): public Component add(Component component) public Component add(Component component, int position) public Component add(Component component, Object constraints) public void remove(Component component) public void remove(int position)

Containers (cont. ) n Layout Manager: public int get. Layout() public void set. Layout(Layout. Manager manager) n Listeners: public void add. Container. Listener( Container. Listener listener) public void remove. Container. Listener( Container. Listener listener)

Window public n void pack() to. Front() to. Back() dispose() Listeners: public void add. Window. Listener( Window. Listener listener) public void remove. Window. Listener( Window. Listener listener)

Frame n Title: public String get. Title() public void set. Title(String title) n Resizable: public boolean is. Resizable() public void set. Resizable(boolean visible) n Border: public Border get. Border() public void set. Border(Border border) n Ancestors: public JRoot. Pane get. Root. Pane() public Container get. Top. Level. Ancestor() n Transparency: public void set. Opaque(boolean is. Opaque) public boolean is. Opaque()

JFrame n Components: public Container get. Content. Pane () JMenu. Bar get. JMenu. Bar () JRoot. Pane get JRoot. Pane () void set. Content. Pane(Container content. Pane) public void set. JMenu. Bar(JMenu. Bar menubar) n Default close operation: public int get. Default. Close. Operation () public void set. Default. Close. Operation (int operation) n One of the following must be passed to set. Default. Close. Operation. Window. Constants. DO_NOTHING_ON_CLOSE Window. Constants. HIDE_ON_CLOSE Window. Constants. DISPOSE_ON_CLOSE

We’ve covered n n n Building a user interface. Event-driven, graphical user interfaces. Java’s facilities for user interfaces. Events. Listeners.

Glossary

Glossary (cont. )
- Slides: 81