The Abstract Window Toolkit

Similar documents
Starting Out with Java: From Control Structures Through Objects Sixth Edition

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects

Java. GUI building with the AWT

GUI in Java TalentHome Solutions

CHAPTER 2. Java Overview

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Graphical User Interfaces. Comp 152

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

AP CS Unit 11: Graphics and Events

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

The AWT Event Model 9

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Packages: Putting Classes Together

Programming Language Concepts: Lecture 8

Java Event Handling -- 1

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Chapter 1 GUI Applications

GUI Programming: Swing and Event Handling

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

GUI Event Handlers (Part I)

PIC 20A GUI with swing

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Swing from A to Z Some Simple Components. Preface

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

BASICS OF GRAPHICAL APPS

Basicsof. JavaGUI and SWING

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Sri Vidya College of Engineering & Technology

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

7. Program Frameworks

Swing from A to Z Using Focus in Swing, Part 2. Preface

Chapter 7: A First Look at GUI Applications

Laying Out Components. What is Widget Layout?

Java AWT Windows, Text, & Graphics

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

Java - Applets. public class Buttons extends Applet implements ActionListener

AWT DIALOG CLASS. Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Graphical Interfaces

Graphical Applications

Graphical Interfaces

An Introduction To Graphical User Interfaces

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Graphical User Interface (GUI)

Graphical User Interfaces in Java - SWING

Graphical User Interface (GUI)

Java Applets / Flash

BM214E Object Oriented Programming Lecture 13

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Part 3: Graphical User Interface (GUI) & Java Applets

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Chapter 12 Advanced GUIs and Graphics

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

MIT AITI Swing Event Model Lecture 17

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Introduction to the JAVA UI classes Advanced HCI IAT351

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Advanced Java Programming

The AWT Package, Placing Components in Containers, CardLayout. Preface. Introduction

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Building Graphical User Interfaces. GUI Principles

CSC207H: Software Design Lecture 11

Class 16: The Swing Event Model

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Building Graphical User Interfaces. Overview

Java Programming Lecture 6

Dr. Hikmat A. M. AbdelJaber

Systems Programming Graphical User Interfaces

To gain experience using GUI components and listeners.

JAVA NOTES GRAPHICAL USER INTERFACES

Programming Languages and Techniques (CIS120e)

Part I: Learn Common Graphics Components

Midterm assessment - MAKEUP Fall 2010

Swing/GUI Cheat Sheet

SD Module-1 Advanced JAVA

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

SD Module-1 Advanced JAVA. Assignment No. 4

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Today. cisc3120-fall2012-parsons-lectiii.3 2

Laborator 2 Aplicatii Java

Transcription:

Chapter 12 The Abstract Window Toolkit 1

12.1 Overview Java s Abstract Window Toolkit provides classes and other tools for building programs that have a graphical user interface. The term Abstract refers to the AWT s ability to run on multiple platforms. Building a GUI involves creating abstract components such as buttons and windows, which are then mapped to concrete components for a specific platform. 2

Swing Java has a newer library for building graphical user interfaces, known as Swing. Swing is more powerful and sophisticated than the AWT. Swing is built around the existing AWT, so it helps to understand the AWT first. Swing is similar enough to the AWT that it s relatively easy to switch if the need arises. Many Swing classes correspond to AWT classes. For example, Swing s JButton class corresponds to the AWT s Button class. 3

Creating a Graphical User Interface GUI programming in Java is based on three concepts: Components. A component is an object that the user can see on the screen and in most cases interact with. Containers. A container is a component that can hold other components. Events. An event is an action triggered by the user, such as a key press or mouse click. Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events. 4

Creating a Graphical User Interface Components are objects, so they re created by invoking a constructor. A button would be created by using a constructor belonging to the Button class. The most commonly used constructor has one argument (the button s label): Button b = new Button("Testing"); For a component to be visible, it must be added to a container (typically a frame) by the add method. 5

Creating a Graphical User Interface To detect when an event occurs, a special listener object can be attached to a component. When the user performs an action that involves the component, a method belonging to the listener object will be called automatically. 6

12.2 Frames In Java terminology, a frame is a window with a title and a border. A frame may also have a menu bar. Frames play an important role in the AWT because a GUI program normally displays a frame when it s executed. 7

The Frame Class Frames are created using one of the constructors in the Frame class. One constructor takes a single argument (the title to be displayed at the top of the frame): Frame f = new Frame("Title goes here"); Although the Frame object now exists, it s not visible on the screen. Before making the frame visible, a method should be called to set the size of the frame. If desired, the frame s location can also be specified. 8

Frame Methods Many methods used with Frame objects are inherited from Window (Frame s superclass) or from Component (Window s superclass). The setsize method sets the width and height of a frame: f.setsize(width, height); If a program fails to call setsize or pack before displaying a frame, it will assume a default size. 9

Frame Methods The size of a frame can change during the execution of a program. The getsize method returns a frame s current width and height: Dimension framesize = f.getsize(); framesize.width will contain f s width. framesize.height will contain f s height. 10

Frame Methods The setvisible method controls whether or not a frame is currently visible on the screen. Calling setvisible with true as the argument makes a frame visible: f.setvisible(true); Calling it with false as the argument makes the frame disappear from the screen: f.setvisible(false); The Frame object still exists; it can be made to reappear later by calling setvisible again. 11

Creating a Frame The FrameTest program creates a Frame object and displays it on the screen. This program illustrates three key steps: 1. Using the Frame constructor to create a frame. 2. Setting the size of the frame. 3. Displaying the frame on the screen. 12

FrameTest.java // Displays a frame on the screen. // WARNING: Frame cannot be closed. import java.awt.*; public class FrameTest { public static void main(string[] args) { Frame f = new Frame("Frame Test"); f.setsize(150, 100); f.setvisible(true); } } 13

Creating a Frame Frame created by the FrameTest program: As with the other AWT components, the appearance of a frame depends on the platform. 14

Creating a Frame Clicking on the Close button has no effect, because there s no action associated with that button. The frame will have be closed the hard way, by killing the program. In Windows, click on the DOS window from which the program was launched, hold down the Ctrl key, and press the letter C. 15

Setting the Location of a Frame By default, all windows (including frames) are displayed in the upper-left corner of the screen, which has coordinates (0, 0). The setlocation method can be used to specify a different location: f.setlocation(50, 75); To find the current location of a frame, call getlocation: Point framelocation = f.getlocation(); The coordinates of f s upper-left corner will be stored in framelocation.x and framelocation.y. 16

Adding Components to a Frame The Frame class is rarely used to create objects directly. Instead, it s customary to define a subclass of Frame and then create an instance of the subclass. This strategy makes it possible to tailor the subclass. In particular, the constructor for the subclass can put components into the frame. 17

Adding Components to a Frame To add a component to a frame (or any kind of container), the add method is used. add belongs to the Container class, so it s inherited by Frame and the other container classes. An example of adding a button to a frame: Button b = new Button("Testing"); add(b); These statements would normally go in the constructor for the frame class. 18

Adding Components to a Frame ButtonTest is a modified version of FrameTest. ButtonTest defines a subclass of Frame named ButtonTestFrame, and then creates an instance of ButtonTestFrame. Actions taken by the ButtonTestFrame constructor: 1. Invokes the superclass constructor (the constructor for Frame), passing it the title of the frame. 2. Calls setlayout to specify how the components inside the frame will be laid out. 3. Creates a Button object. 4. Calls add to add the button to the frame. 19

ButtonTest.java // Displays a frame containing a single button. // WARNING: Frame cannot be closed. import java.awt.*; // Driver class public class ButtonTest { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } // Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Testing"); add(b); } } Do we save two classes in the same java file? 20

Adding Components to a Frame Frame created by the ButtonTest program: Pressing the Testing button has no effect. 21

Adding Components to a Frame Instead of calling setsize, the main method in ButtonTest could have called pack: f.pack(); pack makes the frame just large enough to display the components within it: Regardless of whether setsize or pack is called, the user can manually resize the frame. 22

Adding Components to a Frame It s not necessary to have two separate classes, (ButtonTest and ButtonTestFrame). By moving the main method from ButtonTest to ButtonTestFrame, the program could be condensed to one class (ButtonTestFrame). 23

Exercise Create a window that has three buttons. What are the main steps? 24

12.3 Event Listeners When the user performs an action, Java creates an object containing information about the event. Responding to an event is done by writing a method that can be called when the event occurs. Steps involved in handling an event: 1. The user performs an action, causing an event to be triggered (or fired). 2. An object is created that contains information about the event, including an indication of which component was involved. 3. A method that belongs to a listener object is called. The object created in step 2 is passed to the method. 25

Events When an event occurs, an object is created that contains information about the event. This object will belong to one of several different classes, depending on the nature of the event. These classes all belong to the java.awt.event package. Java divides events into two groups: high-level events and low-level events. 26

High-level events: Class Name Events Description of Event ActionEvent A significant action has been performed on a component (a button was pressed, a list item was double-clicked, or the Enter key was pressed in a text field). AdjustmentEvent The state of an adjustable component (such as a scrollbar) has changed. ItemEvent An item has been selected (or deselected) within a checkbox, choice menu, or list. TextEvent The contents of a text area or text field have changed. 27

Events Low-level events include moving the mouse or pressing a key. One low-level event is WindowEvent, which occurs when the status of a window has changed. In particular, a WindowEvent occurs when the user attempts to close a window. 28

Interfaces Event-handling requires the use of interfaces. An interface looks like a class, except that its methods aren t fully defined. Each method in an interface has a name, a parameter list, and a result type, but no body. One common interface is named ActionListener: public interface ActionListener extends EventListener { public void actionperformed(actionevent evt); } This resembles a class declaration, except that the word class has been replaced by interface, and the actionperformed method has no body. 29

Interfaces An interface is nothing but a pattern that will be used later to define real classes. A class implements an interface by agreeing to provide bodies for all methods in the interface. A class that implements the ActionListener interface would have to provide a method named actionperformed with one parameter of type ActionEvent and a result type of void. 30

Interfaces The keyword implements is used to tell the compiler that a class will implement a particular interface. A class that implements the ActionListener interface: class class-name implements ActionListener { public void actionperformed(actionevent evt) { } // Variables, constructors, and methods, // if desired } The class may contain any number of variables, constructors, and methods. 31

Creating Event Listeners To handle an event, it s necessary to create an event listener object. This object will be registered with a component; when an event occurs that involves the component, one of the listener s methods will be called. An event listener will be an instance of a listener class defined by the programmer. 32

Creating Event Listeners A listener class must implement one of the interfaces that belong to the java.awt.event package. Listener interfaces for high-level events: Interface Name ActionListener Required Method actionperformed(actionevent evt) AdjustmentListener adjustmentvaluechanged(adjustmentevent evt) ItemListener TextListener itemstatechanged(itemevent evt) textvaluechanged(textevent evt) Each interface contains a single method. The access modifier for each method is public, and the result type is void. 33

Creating Event Listeners There s a similar set of listener interfaces for lowlevel events. The listener interface for WindowEvent is named WindowListener. 34

Creating Event Listeners Pressing a button is an action event, so the listener class for a button would need to implement the ActionListener interface. To implement this interface, the class must define a public void method named actionperformed with a parameter of type ActionEvent. An example of a listener for an action event: class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { } } 35

Creating Event Listeners After writing a listener class, the next step is to create an instance of the class and connect it to a particular component. In the simplest case, a single listener object will be attached to a single component. Suppose that b is a Button object: Button b = new Button("Change Color"); A listener object can be created by using the constructor for the listener class: ButtonListener listener = new ButtonListener(); 36

Creating Event Listeners listener can now be registered as an action listener for the button: b.addactionlistener(listener); It s sometimes possible to save a statement by combining the creation of the listener object with the call of addactionlistener: b.addactionlistener(new ButtonListener()); 37

Creating Event Listeners Calling addactionlistener creates a link between the Button object and its listener: When the user presses the button, the ButtonListener object s actionperformed method will be called. 38

Creating Event Listeners Because ButtonListener implements the ActionListener interface, the compiler can verify that it has an actionperformed method. The ActionListener interface acts as a sort of contract that ButtonListener agrees to honor. It s an error to pass an object to addactionlistener unless the object belongs to a class that implements ActionListener. 39

Creating Event Listeners The ButtonTest program displays a Testing button, but pressing the button has no effect. Making the button work involves defining a listener class that implements the ActionListener interface, creating an instance of the class, and attaching it to the button. The ButtonTest2 program is similar to ButtonTest, but the window will close when the button is pressed. Changes are highlighted in bold. 40

ButtonTest2.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing the button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest2 { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } 41

// Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Close window"); add(b); b.addactionlistener(new ButtonListener()); } } // Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { System.exit(0); } } 42

Creating Event Listeners Frame created by the ButtonTest2 program: 43

Creating Event Listeners Pressing the Close window button causes a call of the actionperformed method for the button s listener object. This method calls System.exit, which causes the program to terminate and the frame to disappear. When a program terminates, any windows that it created are automatically closed. 44

Adapter Classes To make the Close button work, a WindowEvent listener is needed. A class that implements the WindowListener interface would have to contain several methods. There s an easier technique: use the WindowAdapter class from the java.awt.event package. This class implements the WindowListener interface, although the methods that it provides are all empty. 45

Adapter Classes The listener class will extend the WindowAdapter class and override the windowclosing method. It will then inherit all the other methods it needs. WindowAdapter is an example of an adapter class a class that can be extended instead of implementing an interface. Java provides matching adapter classes for most interfaces that have two or more methods. 46

Adapter Classes The ButtonTest3 program is a modification of ButtonTest2. The new WindowCloser class extends WindowAdapter and provides a windowclosing method of its own. The constructor for ButtonTestFrame now calls addwindowlistener to install a WindowCloser object as a listener for window events. 47

ButtonTest3.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing either the // "Close window" button or the frame's "close" button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest3 { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } 48

// Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Close window"); add(b); b.addactionlistener(new ButtonListener()); } } // Attach window listener addwindowlistener(new WindowCloser()); // Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { System.exit(0); } } 49

// Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 50

Adapter Classes When a window event occurs, one of the methods in the WindowCloser class will be called. If the event is caused by the user attempting to close the window, the windowclosing method is called, and the program terminates. Any other window event will cause one of WindowCloser s inherited methods to be called. These methods are empty, so nothing will happen. 51

12.4 Inner Classes The ChangeColor program will also have a single button. Pressing the button will change the background color of the frame. The background will initially be white: 52

The ChangeColor Program Pressing the button once will change the background to black: Pressing it again will cause the background to return to white. 53

The setbackground and getbackground Methods Changing the background color of a frame is done by calling the setbackground method, which is inherited from the Component class: setbackground(color.black); The getbackground method (also inherited from Component) returns the current background color. 54

Writing the ChangeColor Program The button listener in ChangeColor will change the frame s background color instead of causing the program to terminate: class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { if (getbackground() == Color.white) setbackground(color.black); else setbackground(color.white); } } 55

Writing the ChangeColor Program Unfortunately, the compiler won t allow the listener to call getbackground or setbackground, because those methods don t belong to the ButtonListener class or its superclass (Object). The actionperformed method needs to get (and set) the background for the frame, not the background for the ButtonListener object itself (which doesn t have a background, anyway). 56

Writing the ChangeColor Program Problems of this sort are common when writing a listener class because listeners often need access to variables or methods that belong to the frame. There s an easy way to solve such a problem: put the listener class inside the frame class. A class that s nested inside another class is said to be an inner class. Inner class methods have access to variables and methods in the enclosing class, allowing the inner class to serve as a helper for the enclosing class. 57

ChangeColor.java // Displays a frame containing a single button. Pressing the // button causes the background of the frame to change from // white to black or from black to white. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 58

// Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.white); // Add "Change color" button to frame and attach listener Button b = new Button("Change color"); add(b); b.addactionlistener(new ButtonListener()); } // Attach window listener addwindowlistener(new WindowCloser()); 59

// Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { if (getbackground() == Color.white) setbackground(color.black); else setbackground(color.white); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 60

12.5 Attaching Listeners to Multiple Components If a program has two buttons, one possibility is to attach the second button to the same ButtonListener object: The ButtonListener object s actionperformed method will be called when either button is pressed. 61

Using Multiple Listeners The other possibility is to create a different listener object for the second button: 62

Using Multiple Listeners The second listener could be an instance of a different listener class: 63

Determining the Source of an Event If two or more buttons are connected to a single listener, its actionperformed method will need to determine which button was pressed. Ways to solve this problem: Compare the source of the event (the component that triggered the method call) to see which Button object it matches. Test the event s action command to see which button label it matches. 64

The getsource Method If evt is an instance of any event class, the source of the event can be found by calling getsource: Object source = evt.getsource(); Because events can be caused by a variety of components, getsource returns an Object reference. To determine which component fired the event, the value returned by getsource can be compared with the variables containing the components: if (source == testbutton) 65

The getactioncommand Method The other way to determine the origin of a button press is to use the getactioncommand method. String label = evt.getactioncommand(); This method can be used only with action events, such as button presses. In the case of a button press, getactioncommand returns the label on the button. A statement that checks whether the button labeled "Testing" was pressed: if (label.equals("testing")) 66

Example: A Single Listener The ChangeColor2 program displays two buttons, labeled Lighter and Darker : 67

Example: A Single Listener Pressing the Lighter button will lighten the background slightly: 68

Example: A Single Listener Pressing Darker will darken it: Each button can be pressed more than once, causing the background to become successively lighter or darker. 69

Example: A Single Listener It s possible to use a single listener object for both buttons. Alternatively, there could be two listeners, one for each button. The ChangeColor2 program will use a single listener. The listener s actionperformed method will determine which button was pressed by testing the string returned by getactioncommand. There are only two buttons, so the string will be either "Lighter" or "Darker". 70

ChangeColor2.java // Displays a frame containing two buttons. Pressing the // "Lighter" button lightens the background of the frame. // Pressing the "Darker" button darkens the background. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor2 { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 71

// Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.gray); } // Create button listener ButtonListener listener = new ButtonListener(); // Add "Lighter" button to frame and attach listener Button b = new Button("Lighter"); add(b); b.addactionlistener(listener); // Add "Darker" button to frame and attach listener b = new Button("Darker"); add(b); b.addactionlistener(listener); // Attach window listener addwindowlistener(new WindowCloser()); 72

// Listener for both buttons class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { Color currentbackground = getbackground(); String buttonlabel = evt.getactioncommand(); } } // Test label on button and change background color if (buttonlabel.equals("lighter")) setbackground(currentbackground.brighter()); else setbackground(currentbackground.darker()); } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 73

Example: A Single Listener The brighter and darker methods belong to the Color class. brighter returns a brighter version of the Color object that called it; darker returns a darker version. 74

Example: Separate Listeners The ChangeColor3 program is similar to ChangeColor2, except that it uses separate listeners for the Lighter and Darker buttons. Using separate listeners requires an additional listener class. On the other hand, the actionperformed method in each class will be very short, because there s no need to test which button was pressed. 75

ChangeColor3.java // Displays a frame containing two buttons. Pressing the // "Lighter" button lightens the background of the frame. // Pressing the "Darker" button darkens the background. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor3 { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 76

// Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.gray); // Add "Lighter" button to frame and attach listener Button b = new Button("Lighter"); add(b); b.addactionlistener(new LighterButtonListener()); // Add "Darker" button to frame and attach listener b = new Button("Darker"); add(b); b.addactionlistener(new DarkerButtonListener()); } // Attach window listener addwindowlistener(new WindowCloser()); 77

// Listener for "Lighter" button class LighterButtonListener implements ActionListener { public void actionperformed(actionevent evt) { setbackground(getbackground().brighter()); } } // Listener for "Darker" button class DarkerButtonListener implements ActionListener { public void actionperformed(actionevent evt) { setbackground(getbackground().darker()); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 78

Exercise Create a window with three buttons as described below: Button 1: the number button. Click this button generate a random number between 0 and 1 and shows the number on the button. Button 2: the number button. Click this button generate a random number between 0 and 1 and shows the number on the button. Button 3: the add button. Click this button will add the numbers of button 1 and button 2 and print the result. 79

12.6 Layout The layout of components within a container remains a mystery. Consider the ChangeColor2 frame: Why are the buttons placed side by side? Why are the buttons centered within the frame? 80

Layout Managers These decisions are made by an object known as a layout manager. Every container has a default layout manager that determines the sizes and positions of components within the container. This layout manager can be replaced if desired. One reason that Java uses layout managers is so that containers can be resized gracefully. Each time a container is resized, the container s layout manager determines new sizes and positions for the components in the container. 81

Layout Manager Classes The java.awt package provides five layout manager classes: Class Name BorderLayout CardLayout FlowLayout 82 Behavior Arranges components along the sides of the container and in the middle. Arrange components in cards. Only one card is visible at a time. Arranges components in variable-length rows. GridBagLayout Aligns components horizontally and vertically; components can be of different sizes. GridLayout Arranges components in fixed-length rows and columns.

Layout Manager Classes FlowLayout and GridLayout are the easiest layout managers to understand. BorderLayout and CardLayout are somewhat harder to use. GridBagLayout is the most powerful layout manager, but it s also the most complicated. 83

Layout Manager Classes Choosing a layout manager is done by calling the setlayout method. (setlayout belongs to the Container class, so it s inherited by all container classes.) To select FlowLayout as the layout manager for a frame, put the following call of setlayout in the frame s constructor: setlayout(new FlowLayout()); If no layout manager is specified for a frame, the default is BorderLayout. 84

The FlowLayout Class The FlowLayout layout manager can handle any number of components. The components are laid out side by side from left to right. When no more components will fit in a row, FlowLayout starts a new row. 85

The FlowLayout Class Suppose that a frame containing seven buttons uses FlowLayout as its layout manager. The number of buttons that can be squeezed into a row depends on how wide the frame is: 86

The FlowLayout Class The simplest way to use FlowLayout is to call its no-arg constructor and pass the resulting object to setlayout: setlayout(new FlowLayout()); By default, components will be separated by five pixels of space and centered in each row. 87

The FlowLayout Class The alignment can be specified explicitly by passing FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER to the constructor: setlayout(new FlowLayout(FlowLayout.LEFT)); The horizontal and vertical gaps between components can also be passed to the constructor: setlayout(new FlowLayout(FlowLayout.LEFT, 20, 10)); 88

The GridLayout Class The GridLayout layout manager places components in rows, with each row (except possibly the last) having an equal number of components: 89

The GridLayout Class If a frame with a GridLayout is resized, the components within the frame change size as well: 90

The GridLayout Class The GridLayout constructor requires that the number of rows and columns be specified: setlayout(new GridLayout(4, 5)); Components will be arranged in four rows and five columns, with no space between components. If space is desired between components, two more arguments the horizontal gap and the vertical gap are supplied to the constructor: setlayout(new GridLayout(4, 5, 20, 10)); 91

The GridLayout Class GridLayout works best when all components in the container are the same kind (all buttons, for example), because it forces the components to be the same size. If the container contains a mixture of components, some components may end up appearing too large while others look too small. 92

The BorderLayout Class The BorderLayout layout manager can handle up to five components. Four of the components can be positioned against the sides of the container, with the fifth occupying the center of the container. 93

The BorderLayout Class The positions in a BorderLayout are named North, South, East, West, and Center: 94

The BorderLayout Class The North and South components are stretched to the width of the container. The West and East components are stretched vertically to fill the gap between North and South. The Center component expands in both directions to fill any remaining space. 95

The BorderLayout Class The no-arg version of the BorderLayout constructor leaves no space between components: setlayout(new BorderLayout()); A different constructor is used if space is needed between components: setlayout(new BorderLayout(20, 10)); 96

The BorderLayout Class When a container uses BorderLayout as its layout manager, a different version of the add method is required: add("center", new Button("Test")); The first argument must be either "North", "South", "East", "West", or "Center". 97

The BorderLayout Class If a frame with a BorderLayout is resized, the heights of the North and South components don t change: The widths of the East and West components also remain the same. 98

The BorderLayout Class BorderLayout doesn t require that all five positions be used; unused positions are filled by neighboring components. This property makes BorderLayout a surprisingly versatile layout tool. 99

Preferred Sizes Every component has a preferred size. For example, the preferred size of a button is determined by the size of the label on the button the longer the label, the wider the button. 100

Preferred Sizes Each layout manager has a different way of dealing with preferred sizes: FlowLayout: Honors the preferred sizes of all components. GridLayout: Ignores the preferred sizes of all components. BorderLayout: Honors the preferred widths of the East and West components. Honors the preferred heights of the North and South components. Ignores the preferred size of the Center component. 101

Preferred Sizes The layout examples shown earlier illustrate this behavior: The buttons in the FlowLayout example stayed the same size (their preferred size), no matter what the size of the frame was. The buttons in the GridLayout example expanded to fill the entire frame. In the BorderLayout example, the North and South buttons kept their preferred height, while the East and West buttons kept their preferred width. 102

Panels A panel an instance of the Panel class is another kind of container. A panel is rectangular but has no border. When a panel is placed inside another container, it blends in seamlessly. Each panel has its own layout manager. A panel can be used to create a group of components that is treated as a single component. 103

Panels Panel objects can be created by using the no-arg version of the Panel constructor: Panel p = new Panel(); By default, the layout manager for a panel is FlowLayout. A different layout manager can be chosen by calling setlayout: p.setlayout(new BorderLayout()); Passing the layout manager to the Panel constructor avoids a separate call of setlayout: Panel p = new Panel(new BorderLayout()); 104

Panels Once a panel has been created, components are added to it by calling the add method: p.add("center", new Button("Test")); The panel itself will need to be added to a frame or other container. 105

Panels Consider the problem of creating a frame with the following appearance: 106

Panels The top 12 buttons will need to be grouped into a single component using a panel. The panel will use a GridLayout to force the buttons into four rows and three columns. To make sure that this panel is positioned above the Dial button, the frame itself will need to use a BorderLayout. If the Dial button is placed at the South position and the panel at the Center position, the panel will expand to fill the frame. 107

Panels To keep the Dial button at the correct size, it will need to be put in a panel of its own, which is then placed at the South position. This panel will have a FlowLayout manager, which will center the button and keep it at its preferred size. The panel containing the 12 buttons will also need to be put inside another panel, to keep the buttons from growing if the frame is resized. 108

Panels Summary of panels needed: buttonpanel: Contains 12 buttons; uses GridLayout. centerpanel: Contains buttonpanel; uses FlowLayout. bottompanel: Contains Dial button; uses FlowLayout. 109

Panels A figure showing the panels as dashed rectangles: 110

Panels Statements to create the phone layout: Panel buttonpanel = new Panel(); buttonpanel.setlayout(new GridLayout(4, 3, 10, 10)); for (int i = 1; i <= 9; i++) buttonpanel.add(new Button(i + "")); buttonpanel.add(new Button("*")); buttonpanel.add(new Button("0")); buttonpanel.add(new Button("#")); Panel centerpanel = new Panel(); centerpanel.add(buttonpanel); add("center", centerpanel); Panel bottompanel = new Panel(); bottompanel.add(new Button("Dial")); add("south", bottompanel); 111

12.7 Creating and Using Components For each component, it s important to know three things: How to create the component What kind of event(s) it fires How to determine the current state of the component 112

Checkboxes A checkbox is a small box that the user can check by clicking with the mouse: Clicking on the box causes a check mark to appear: Clicking a second time removes the check mark from the box. 113

Checkboxes A checkbox normally has a label, which is passed to the Checkbox constructor as an argument: Checkbox cb = new Checkbox("Enable sounds"); The no-arg version of the Checkbox constructor creates a checkbox without a label: Checkbox cb = new Checkbox(); By default, a new checkbox is in the off state (no check mark). Creating a checkbox that s on requires using a constructor that takes the state as its second argument: Checkbox cb = new Checkbox("Enable sounds", true); 114

Checkboxes When a checkbox is clicked, an item event occurs. Detecting this event requires writing a listener class that implements the ItemListener interface. Implementing this interface requires writing a method named itemstatechanged: class CheckboxListener implements ItemListener { public void itemstatechanged(itemevent evt) { } } The additemlistener method can be used to attach a listener to the checkbox: cb.additemlistener(new CheckboxListener()); 115

Checkboxes Not every checkbox will require a listener. A program may wait for some other event to occur and then examine the checkboxes to see which ones are currently checked. The getstate method returns the state of a checkbox: boolean state = cb.getstate(); The setstate method changes the state of a checkbox: cb.setstate(true); 116

Checkbox Groups A checkbox group is a collection of checkboxes in which only one box can be checked at a time: Checkboxes that are related in this way are often referred to as radio buttons. Checkboxes that belong to a group often have a different appearance than individual checkboxes. Under Windows, boxes in a group are round instead of square. 117

Checkbox Groups The first step in creating a group of checkboxes is to create a CheckboxGroup object: CheckboxGroup musicgroup = new CheckboxGroup(); The next step is to create the checkboxes, supplying the CheckboxGroup object as the second argument to the Checkbox constructor: Checkbox rockbox = new Checkbox("Rock", musicgroup, true); Checkbox jazzbox = new Checkbox("Jazz", musicgroup, false); Checkbox classicalbox = new Checkbox("Classical", musicgroup, false); 118

Choice Menus A choice menu (or popup menu) displays one of several items: When the user presses on the arrow button with the mouse, the full list of choices pops up: 119

Choice Menus Creating a choice menu requires two steps. The first step is to create a Choice object: Choice countrychoice = new Choice(); The second step is to add menu items using the add method: countrychoice.add("u.s.a."); countrychoice.add("canada"); countrychoice.add("mexico"); The order in which the items are added determines the order in which they ll appear on the menu. 120

Choice Menus When the user pops up the menu and makes a choice, an item event occurs. As a result, the listener class for a choice menu will need to implement the ItemListener interface. The getselecteditem method returns the selected item: String itemselected = countrychoice.getselecteditem(); The getselectedindex method returns the position of the selected item: int itemindex = countrychoice.getselectedindex(); The first item in the list has index 0. 121

Labels A label is a rectangular area containing a text string: A label has no border around it; the user sees nothing but the text. Labels are often placed next to other components to indicate their meaning or function. The user can t change a label s text; there are no events defined for labels. 122

Labels One of the Label constructors takes a single argument, the text to be displayed within the label: Label lastname = new Label("Enter last name:"); By default, the text is left-justified within the label. The desired alignment can be passed as a second argument to the Label constructor: Label lastname = new Label("Enter last name:", Label.CENTER); Possible values are Label.CENTER, Label.LEFT, and Label.RIGHT. 123

Labels The gettext method returns the text of a label: String labelcontents = lastname.gettext(); The settext method changes the text of a label: lastname.settext("enter first name:"); 124

Lists A list is a rectangle containing a series of items: The user can choose an item by clicking on it: 125

Lists If not all list items are visible, a scrollbar appears to the right of the list: 126

Lists Creating a list is similar to creating a choice menu. The first step is to create a List object: List countrylist = new List(); By default, four items will be visible at a time. The number of visible items can be specified if desired: List countrylist = new List(5); Once the list has been created, the add method is used to add items to it: countrylist.add("u.s.a."); countrylist.add("canada"); countrylist.add("mexico"); 127

Lists Single-clicking on a list item causes an item event. Double-clicking causes an action event. To determine which item was selected, either getselectedindex or getselecteditem can be called. 128

Scrollbars A scrollbar is a sliding bar. Scrollbars can be either horizontal: or vertical: 129

Scrollbars Each scrollbar represents a number chosen from a range of integers, such as 0 to 100 or 32 to 212. The width of the sliding portion of the scrollbar (the scroll box or bubble ) must be at least 1 (measured in the scrollbar s own units, not in pixels), but it can be wider if desired. 130

Scrollbars The largest value that the user can select is the maximum value of the scrollbar s range minus the width of the scroll box. If the scrollbar has a range of 0 to 100, and the scroll box has a width of 10, then the largest value that the user can select is 100 10 = 90. 131

Scrollbars Ways for the user to change the value of a scrollbar: Drag the scroll box to a different position. Click on the arrow buttons, which changes the value by a small amount, known as the unit increment. (By default, the unit increment is 1.) Click in the area between an arrow button and the scroll box, which changes the value by a larger amount, known as the block increment. (By default, the block increment is 10.) 132

Scrollbars One Scrollbar constructor has five arguments: Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 50, 1, 0, 100); The first argument (Scrollbar.HORIZONTAL or Scrollbar.VERTICAL) specifies the scrollbar s orientation. The fourth and fifth arguments specify the minimum and maximum values of the scrollbar s range. The second argument is the initial value of the scrollbar. The third argument is the width of the scroll box, which must be at least 1. 133

Scrollbars When the user adjusts a scrollbar, an adjustment event occurs. Handling the event requires writing a class that implements the AdjustmentListener interface. This class must contain a method named adjustmentvaluechanged: class ScrollbarListener implements AdjustmentListener { public void adjustmentvaluechanged(adjustmentevent evt) { } } 134

Scrollbars The addadjustmentlistener method is used to attach a listener to the scrollbar: sb.addadjustmentlistener(new ScrollbarListener()); The getvalue method returns the current value of a scrollbar: int value = sb.getvalue(); The setvalue method changes the value of a scrollbar: sb.setvalue(newvalue); 135

Text Areas A text area is capable of displaying multiple lines of text: Scrollbars at the bottom and right side make it possible for the user to view text that s not otherwise visible. 136

Text Areas There are four ways to create a TextArea object, depending on: Whether or not text is to be displayed initially. Whether the number of rows and columns is specified. 137

Text Areas Assume that quote is the following string: String quote = "To be, or not to be: that is the question:\n" + "Whether 'tis nobler in the mind to suffer\n" + "The slings and arrows of outrageous fortune,\n" + "Or to take arms against a sea of troubles,\n" + "And by opposing end them? To die: to sleep;\n" + "No more; and, by a sleep to say we end\n" + "The heartache and the thousand natural shocks\n" + "That flesh is heir to, 'tis a consummation\n" + "Devoutly to be wish'd. To die, to sleep;\n" + "To sleep: perchance to dream: ay, there's the rub;\n" + "For in that sleep of death what dreams may come"; Notice that new-line characters are used to separate lines. 138

Text Areas The no-arg constructor creates an empty text area with a default size: TextArea ta = new TextArea(); To create a nonempty text area, a string containing the desired text is passed as an argument: TextArea ta = new TextArea(quote); The number of rows and columns can be specified: TextArea ta = new TextArea(10, 20); It s also possible to specify values for both the text and the rows and columns: TextArea ta = new TextArea(quote, 10, 20); 139

Text Areas A text area can be made editable or not editable by calling seteditable and passing either true or false: ta.seteditable(false); // Not editable Text areas are editable by default. A text event occurs whenever the user changes any of the text in a text area. 140

Text Areas Detecting a text event requires writing a class that implements the TextListener interface. Implementing this interface involves writing a method named textvaluechanged: class TextAreaListener implements TextListener { public void textvaluechanged(textevent evt) { } } The addtextlistener method attaches a listener to a text area: ta.addtextlistener(new TextAreaListener()); 141

Text Areas The gettext method returns the current contents of a text area: String text = ta.gettext(); gettext returns a single string, with new-line characters marking breaks between lines. The settext method replaces the contents of a text area: ta.settext("line 1\nLine 2\nLine 3"); The append method adds text to the end of a text area: ta.append("\nline 4"); 142

Text Fields A text field contains a single line of text: The TextField class has four constructors, whose arguments specify the contents of the text field and/or the number of columns in the text field: TextField tf = new TextField(); TextField tf = new TextField("Your name here"); TextField tf = new TextField(40); TextField tf = new TextField("Your name here", 40); 143

Text Fields Text fields are editable by default. A text field can be made not editable by calling seteditable with false as the argument: tf.seteditable(false); // Not editable A text field can fire text events, which occur when the user modifies the contents of the text field. An action event occurs when the user presses the Enter key after entering data into a text field. Both text events and action events are possible only if the text field is editable. 144

Text Fields The methods for text fields, which include gettext and settext, are similar to those for text areas. This similarity isn t surprising, because the TextArea and TextField classes inherit much of their behavior from their superclass, TextComponent. Text fields don t support the append method, however. 145

12.8 Examples The ConvertTemp, ShowDefinition, and PickColor programs illustrate the use of various GUI components. 146

Using Labels and Text Fields: Temperature Conversion ConvertTemp is a GUI version of the Chapter 2 program that converts Fahrenheit temperatures to Celsius. The new version will also be able to convert temperatures from Celsius to Fahrenheit. ConvertTemp will display the following frame: 147

Using Labels and Text Fields: Temperature Conversion If the user enters a value in the Fahrenheit field and presses the Enter key, the corresponding Celsius temperature will appear in the Celsius field: 148

Using Labels and Text Fields: Temperature Conversion Likewise, if the user enters a value in the Celsius field and presses the Enter key, the corresponding Fahrenheit temperature will appear in the Fahrenheit field: Temperatures displayed by the program will be rounded to two decimal places. 149

Using Labels and Text Fields: Temperature Conversion Designing this program requires confronting two issues: layout and event-handling. The GUI components will be two labels and two text fields. The layout manager can be GridLayout with two rows and two columns. GridLayout will make the labels and text fields all the same size. The text fields will need to be declared as instance variables so that a listener will be able to modify one of the text fields when the other is changed. 150

Using Labels and Text Fields: Temperature Conversion ConvertTemp will need at least two listeners. One listener will cause the program to terminate when the user closes the frame. Another listener will be called when the user enters data into either one of the text fields. Although one listener is enough for this purpose, the program is easier to understand if two listeners are used, one for each field. 151

Using Labels and Text Fields: Temperature Conversion The listener classes, FahrenheitListener and CelsiusListener, will each have an actionperformed method. Actions taken by this method: Retrieve the user s input from one of the text fields and convert it to double form. Convert this number from one temperature scale to the other. Round the result to two decimal places and display it in the other text field. Convert.toDouble (from the jpb package) is used to convert the user s input into a double value. 152

ConvertTemp.java // Converts a Fahrenheit temperature entered by the user to // Celsius, or vice versa import java.awt.*; import java.awt.event.*; import jpb.*; // Driver class public class ConvertTemp { public static void main(string[] args) { Frame frame = new ConvertTempFrame("Temperature Conversion"); frame.setsize(150, 75); frame.setvisible(true); } } 153

// Frame class class ConvertTempFrame extends Frame { private TextField fahrenfield = new TextField(); private TextField celsiusfield = new TextField(); // Constructor public ConvertTempFrame(String title) { // Set title for frame and choose layout super(title); setlayout(new GridLayout(2, 2)); // Add Fahrenheit label and text field to frame; attach // listener to text field add(new Label("Fahrenheit")); add(fahrenfield); fahrenfield.addactionlistener(new FahrenheitListener()); 154

// Add Celsius label and text field to frame; attach // listener to text field add(new Label("Celsius")); add(celsiusfield); celsiusfield.addactionlistener(new CelsiusListener()); } // Attach window listener addwindowlistener(new WindowCloser()); // Listener for fahrenfield class FahrenheitListener implements ActionListener { public void actionperformed(actionevent evt) { String fahrenheitstring = fahrenfield.gettext(); double fahrenheit = Convert.toDouble(fahrenheitString); double celsius = (fahrenheit - 32.0) * 5.0 / 9.0; celsius = Math.rint(celsius * 100.0) / 100.0; celsiusfield.settext(celsius + ""); } } 155

// Listener for celsiusfield class CelsiusListener implements ActionListener { public void actionperformed(actionevent evt) { String celsiusstring = celsiusfield.gettext(); double celsius = Convert.toDouble(celsiusString); double fahrenheit = celsius * 9.0 / 5.0 + 32.0; fahrenheit = Math.rint(fahrenheit * 100.0) / 100.0; fahrenfield.settext(fahrenheit + ""); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 156

Using Lists and Text Areas: Showing Definitions The ShowDefinition program illustrates the use of lists and text areas. ShowDefinition will display a list of terms: 157

Using Lists and Text Areas: Showing Definitions When the user clicks on a term, the program will display the definition of the term in the text area: 158

Using Lists and Text Areas: Showing Definitions To make the text area as large as possible, ShowDefinition will use a BorderLayout, with the list of terms at West and the text area at Center. Single-clicking on a list item causes an item event, so the program will need a listener class that implements the ItemListener interface. The text area won t need a listener. 159

Using Lists and Text Areas: Showing Definitions The terms and definitions will be stored in parallel arrays named terms and definitions. When the user clicks on a list item, the getselectedindex method can be used to get the position of the selected term. The program will then display the definition at the same position in the definitions array. 160

ShowDefinition.java // Shows the definition of a term import java.awt.*; import java.awt.event.*; // Driver class public class ShowDefinition { public static void main(string[] args) { Frame f = new ShowDefinitionFrame("Show Definition"); f.setsize(300, 160); f.setvisible(true); } } 161

// Frame class class ShowDefinitionFrame extends Frame { private List termlist = new List(); private TextArea definitionarea = new TextArea(); private String[] terms = {"Button", "Checkbox", "Choice", "Label", "List", "Scrollbar", "TextArea", "TextField"}; private String[] definitions = {"A labeled button that can\nbe pressed", "A box that can be clicked\n\"on\" or \"off\"", "A menu that displays one\nitem at a time", "A string that can be\npositioned next to " + "other\ncomponents", "A scrolling list of items", "A sliding bar that can be\neither horizontal or " + "vertical", "A multiline area in which\ntext can be displayed " + "or\nedited", "A single line of text that\ncan be displayed " + "or\nedited"}; 162

// Constructor public ShowDefinitionFrame(String title) { // Set title for frame super(title); // Put terms in term list; add term list to frame for (int i = 0; i < terms.length; i++) termlist.add(terms[i]); termlist.additemlistener(new ListListener()); add("west", termlist); // Make definition area not editable and add to frame definitionarea.seteditable(false); add("center", definitionarea); } // Attach window listener addwindowlistener(new WindowCloser()); 163

// Listener for termlist class ListListener implements ItemListener { public void itemstatechanged(itemevent evt) { int index = termlist.getselectedindex(); definitionarea.settext(definitions[index]); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 164

Using Labels and Scrollbars: Picking Colors The PickColor program illustrates the use of labels and scrollbars. The program will display a frame containing three scrollbars, representing the colors red, green, and blue, and three labels. 165

Using Labels and Scrollbars: Picking Colors Initially, each scrollbar will be in its middle position, representing the color gray: 166

Using Labels and Scrollbars: Picking Colors By moving the scrollbars, the user can experiment with different color combinations: 167