+ All Categories
Home > Documents > Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W....

Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W....

Date post: 26-Dec-2015
Category:
Upload: sharyl-wilkerson
View: 217 times
Download: 2 times
Share this document with a friend
Popular Tags:
173
Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12: The Abstract Window Toolkit Java Java Programming Programming FROM THE BEGINNING FROM THE BEGINNING Chapter 12 The Abstract Window Toolkit
Transcript
Page 1: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

1

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Chapter 12

The Abstract Window Toolkit

Page 2: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

2

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 3: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

3

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 4: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

4

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 5: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

5

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 6: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

6

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 7: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

7

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

• The DrawableFrame objects used in previous chapters are examples of frames.

Page 8: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

8

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 9: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

9

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 10: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

10

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 11: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

11

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 12: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

12

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 13: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

13

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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); }}

Page 14: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

14

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Creating a Frame

• Frame created by the FrameTest program:

• As with the other AWT components, the appearance of a frame depends on the platform.

Page 15: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

15

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 16: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

16

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 17: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

17

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 18: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

18

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 19: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

19

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 20: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

20

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

ButtonTest.java// Displays a frame containing a single button.// WARNING: Frame cannot be closed.

import java.awt.*;

// Driver classpublic class ButtonTest { public static void main(String[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); }}

// Frame classclass ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setLayout(new FlowLayout()); Button b = new Button("Testing"); add(b); }}

Page 21: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

21

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Adding Components to a Frame

• Frame created by the ButtonTest program:

• Pressing the “Testing” button has no effect.

Page 22: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

22

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 23: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

23

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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).

Page 24: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

24

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 25: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

25

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 26: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

26

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Events

• High-level events:

Class Name Description of EventActionEvent A significant action has been performed on

a component (a button was pressed, a listitem was double-clicked, or the Enter keywas 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 fieldhave changed.

Page 27: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

27

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 28: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

28

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 29: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

29

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 30: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

30

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 31: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

31

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 32: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

32

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Creating Event Listeners

• A listener class must implement one of the interfacesthat belong to the java.awt.event package.

• Listener interfaces for high-level events: Interface Name Required MethodActionListener actionPerformed(ActionEvent evt)

AdjustmentListener adjustmentValueChanged(AdjustmentEvent evt)

ItemListener itemStateChanged(ItemEvent evt)

TextListener textValueChanged(TextEvent evt)

• Each interface contains a single method. The access modifier for each method is public, and the resulttype is void.

Page 33: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

33

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Creating Event Listeners

• There’s a similar set of listener interfaces for low-level events.

• The listener interface for WindowEvent is named WindowListener.

Page 34: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

34

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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) { … }}

Page 35: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

35

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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();

Page 36: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

36

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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());

Page 37: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

37

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 38: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

38

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 39: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

39

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 40: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

40

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ButtonTest2 { public static void main(String[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); }}

Page 41: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

41

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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 buttonclass ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { System.exit(0); }}

Page 42: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

42

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Creating Event Listeners

• Frame created by the ButtonTest2 program:

Page 43: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

43

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 44: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

44

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Adapter Classes

• To make the Close button work, a WindowEvent listener is needed.

• A class that implements the WindowListener interface would have to contain seven 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.

Page 45: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

45

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 46: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

46

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 47: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

47

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ButtonTest3 { public static void main(String[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); }}

Page 48: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

48

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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 buttonclass ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { System.exit(0); }}

Page 49: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

49

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Listener for windowclass WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); }}

Page 50: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

50

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 51: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

51

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 52: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

52

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The ChangeColor Program

• Pressing the button once will change the background to black:

• Pressing it again will cause the background to return to white.

Page 53: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

53

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The setBackground andgetBackground 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.

Page 54: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

54

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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); }}

Page 55: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

55

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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).

Page 56: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

56

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 57: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

57

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ChangeColor { public static void main(String[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setSize(160, 100); f.setVisible(true); }}

Page 58: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

58

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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()); }

Page 59: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

59

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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); } }}

Page 60: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

60

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

12.5 Attaching Listeners toMultiple 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.

Page 61: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

61

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Multiple Listeners

• The other possibility is to create a different listener object for the second button:

Page 62: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

62

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Multiple Listeners

• The second listener could be an instance of a different listener class:

Page 63: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

63

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 64: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

64

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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) …

Page 65: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

65

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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")) …

Page 66: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

66

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Example: A Single Listener

• The ChangeColor2 program displays two buttons, labeled “Lighter” and “Darker”:

Page 67: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

67

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Example: A Single Listener

• Pressing the “Lighter” button will lighten the background slightly:

Page 68: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

68

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 69: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

69

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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".

Page 70: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

70

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ChangeColor2 { public static void main(String[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setSize(160, 100); f.setVisible(true); }}

Page 71: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

71

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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()); }

Page 72: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

72

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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); } }}

Page 73: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

73

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 74: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

74

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 75: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

75

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ChangeColor3 { public static void main(String[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setSize(160, 100); f.setVisible(true); }}

Page 76: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

76

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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()); }

Page 77: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

77

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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); } }}

Page 78: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

78

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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?

Page 79: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

79

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 80: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

80

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Layout Manager Classes

• The java.awt package provides five layout manager classes:

Class Name BehaviorBorderLayout Arranges components along the sides of the

container and in the middle.

CardLayout Arrange components in “cards.” Only onecard is visible at a time.

FlowLayout 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 andcolumns.

Page 81: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

81

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 82: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

82

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 83: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

83

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 84: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

84

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 85: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

85

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 86: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

86

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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));

Page 87: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

87

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The GridLayout Class

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

Page 88: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

88

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The GridLayout Class

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

Page 89: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

89

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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));

Page 90: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

90

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 91: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

91

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 92: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

92

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The BorderLayout Class

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

Page 93: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

93

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 94: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

94

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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));

Page 95: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

95

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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".

Page 96: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

96

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

• 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.

The BorderLayout Class

Page 97: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

97

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 98: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

98

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 99: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

99

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 100: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

100

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 101: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

101

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 102: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

102

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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());

Page 103: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

103

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 104: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

104

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Panels

• Consider the problem of creating a frame with the following appearance:

Page 105: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

105

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 106: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

106

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 107: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

107

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Panels

• Summary of panels needed:buttonPanel: Contains 12 buttons; uses GridLayout.

centerPanel: Contains buttonPanel; uses FlowLayout.

bottomPanel: Contains “Dial” button; uses FlowLayout.

Page 108: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

108

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Panels

• A figure showing the panels as dashed rectangles:

Page 109: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

109

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 110: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

110

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 111: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

111

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 112: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

112

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 113: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

113

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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());

Page 114: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

114

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 115: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

115

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 116: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

116

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 117: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

117

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 118: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

118

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 119: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

119

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 120: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

120

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

• 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.

Labels

Page 121: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

121

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 122: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

122

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:");

Page 123: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

123

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Lists

• A list is a rectangle containing a series of items:

• The user can choose an item by clicking on it:

Page 124: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

124

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Lists

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

Page 125: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

125

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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");

Page 126: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

126

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 127: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

127

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Scrollbars

• A scrollbar is a sliding bar.• Scrollbars can be either horizontal:

or vertical:

Page 128: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

128

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 129: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

129

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 130: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

130

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.)

Page 131: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

131

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 132: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

132

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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)

{ … }}

Page 133: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

133

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 ascrollbar:sb.setValue(newValue);

Page 134: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

134

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 135: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

135

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 136: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

136

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 137: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

137

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 138: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

138

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 139: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

139

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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());

Page 140: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

140

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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");

Page 141: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

141

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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);

Page 142: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

142

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 143: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

143

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 144: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

144

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

12.8 Examples

• The ConvertTemp, ShowDefinition, and PickColor programs illustrate the use of various GUI components.

Page 145: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

145

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 146: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

146

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 147: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

147

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 148: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

148

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 149: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

149

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 150: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

150

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 151: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

151

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 classpublic class ConvertTemp { public static void main(String[] args) { Frame frame = new ConvertTempFrame("Temperature Conversion"); frame.setSize(150, 75); frame.setVisible(true); }}

Page 152: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

152

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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());

Page 153: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

153

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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 + ""); } }

Page 154: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

154

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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); } }}

Page 155: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

155

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 156: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

156

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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:

Page 157: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

157

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 158: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

158

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 159: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

159

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

ShowDefinition.java// Shows the definition of a term

import java.awt.*;import java.awt.event.*;

// Driver classpublic class ShowDefinition { public static void main(String[] args) { Frame f = new ShowDefinitionFrame("Show Definition"); f.setSize(300, 160); f.setVisible(true); }}

Page 160: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

160

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass 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"};

Page 161: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

161

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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()); }

Page 162: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

162

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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); } }}

Page 163: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

163

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 164: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

164

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Labels and Scrollbars:Picking Colors

• Initially, each scrollbar will be in its middle position, representing the color gray:

Page 165: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

165

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Labels and Scrollbars:Picking Colors

• By moving the scrollbars, the user can experiment with different color combinations:

Page 166: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

166

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Labels and Scrollbars:Picking Colors

• As the user moves the scrollbars, the background colors of the labels will change, as will the text of each label.

• The desired layout can be achieved by using a GridLayout with six rows and one column.

• The labels will be created with the Label.CENTER attribute, forcing them to be centered.

Page 167: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

167

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Labels and Scrollbars:Picking Colors

• The listener class will need to implement AdjustmentListener.

• Using a single listener leads to the shortest program.

• The three labels will have to be stored in instance variables so that the listener can change the labels’ background color and text.

• The three scrollbars will also need to be stored in instance variables, for reasons that aren’t so obvious.

Page 168: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

168

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Labels and Scrollbars:Picking Colors

• The listener’s adjustmentValueChanged method will be called when the user adjusts any one of the scrollbars.

• The listener can then call each scrollbar’s getValue method to find the current value of the scrollbar.

• The program doesn’t know which scrollbar was actually changed, but it doesn’t need to.

Page 169: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

169

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

PickColor.java// Allows the user to pick a color by moving three scrollbars

import java.awt.*;import java.awt.event.*;

// Driver classpublic class PickColor { public static void main(String[] args) { Frame f = new PickColorFrame("Pick Color"); f.setSize(150, 200); f.setVisible(true); }}

Page 170: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

170

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Frame classclass PickColorFrame extends Frame { private Label redLabel = new Label("Red = 128", Label.CENTER); private Label greenLabel = new Label("Green = 128", Label.CENTER); private Label blueLabel = new Label("Blue = 128", Label.CENTER); private Scrollbar redBar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 1, 0, 256); private Scrollbar greenBar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 1, 0, 256); private Scrollbar blueBar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 1, 0, 256);

// Constructor public PickColorFrame(String title) { // Set title, background color, and layout super(title); setBackground(new Color(128, 128, 128)); setLayout(new GridLayout(6, 1));

Page 171: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

171

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Create scrollbar listener ScrollbarListener listener = new ScrollbarListener();

// Add red scrollbar and label to frame; attach // listener to scrollbar add(redBar); redBar.addAdjustmentListener(listener); add(redLabel);

// Add green scrollbar and label to frame; attach // listener to scrollbar add(greenBar); greenBar.addAdjustmentListener(listener); add(greenLabel);

// Add blue scrollbar and label to frame; attach // listener to scrollbar add(blueBar); blueBar.addAdjustmentListener(listener); add(blueLabel);

// Attach window listener addWindowListener(new WindowCloser()); }

Page 172: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

172

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Listener for all scrollbars class ScrollbarListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent evt) { int red = redBar.getValue(); int green = greenBar.getValue(); int blue = blueBar.getValue();

redLabel.setText("Red = " + red); greenLabel.setText("Green = " + green); blueLabel.setText("Blue = " + blue);

Color newColor = new Color(red, green, blue); redLabel.setBackground(newColor); greenLabel.setBackground(newColor); blueLabel.setBackground(newColor); } }

Page 173: Chapter 12: The Abstract Window Toolkit Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 12.

Copyright © 2000 W. W. Norton & Company.All rights reserved.

173

Chapter 12: The Abstract Window Toolkit

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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


Recommended