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.
2
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. 3
AWT CLASSHIERARCHY
4
CREATING A GRAPHICAL USER INTERFACE
Components are objects, so they’re created by
invoking a constructor.
A button would be created by using a constructor
belonging to the Button class.
The most commonly used constructor has one
argument (the button’s label):
Button b = new Button("Testing");
For a component to be visible, it must be added to
a container (typically a frame) by the add method.
5
CREATING A GRAPHICAL USER INTERFACE
To detect when an event occurs, a special
“listener” object can be attached to a component.
When the user performs an action that involves
the component, a method belonging to the
listener object will be called automatically.
6
GUI COMPONENT API
Java: GUI component = class
Properties
Methods
Events
Button
USING A GUI COMPONENT 2
1.Create it
2.Configure it
3.Add children (if container)
4.Add to parent (if not Frame)
5.Listen to it
order
important
USING A GUI COMPONENT
1.Create it
Instantiate object:
Button b = new Button();
2.Configure it
Methods: b.setText(“press me”);
3.Add it
panel.add(b);
4.Listen to it
Events: Listeners
Button
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.
11
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.
13
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.
14
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.
15
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);
16
CREATING A FRAME
Frame created by the FrameTest program:
As with the other AWT components, the
appearance of a frame depends on the platform.
18
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.
20
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.
21
ADDING COMPONENTS TO A FRAME
Frame created by the ButtonTest program:
Pressing the “Testing” button has no effect.
23
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.
24
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 blend 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.
25
PANELS
Panel objects can be created by using the no-
arg version of the Panel constructor:
Panel p = new Panel();
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.
26
LAYOUT
The layout of components within a container
remains a mystery.
Consider the FOLLOWING frame:
Why are the buttons placed side by side?
Why are the buttons centered within the frame?
27
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.
28
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:
32
THE GRIDLAYOUT CLASS
The GridLayout layout manager places
components in rows, with each row (except
possibly the last) having an equal number of
components:
34
THE GRIDLAYOUT CLASS
If a frame with a GridLayout is resized, the
components within the frame change size as well:
35
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));
36
THE BORDERLAYOUT CLASS
The positions in a BorderLayout are named
North, South, East, West, and Center:
39
LABELS
A label is a rectangular area containing a text
string:
A label has no border around it; the user sees
nothing but the text.
Labels are often placed next to other components
to indicate their meaning or function.
The user can’t change a label’s text; there are no
events defined for labels.
46
LABELS
Label defines the following constructors:
Label( )
Label(String str)
Label(String str, int how)
The first version creates a blank label.
The second version creates a label that contains the
string specified by str. This string is left-justified.
The third version creates a label that contains the string
specified by str using the alignment specified by how.
The value of how must be one of these three constants:
Label.LEFT, Label.RIGHT, or Label.CENTER.
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.
49
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:");
50
import java.awt.*;
class Label1
{ public static void main(String[] args)
{ Frame f=new Frame("DEMO");
final Label L=new Label("PQRS");
final Label L1=new Label("ABCD");
f.setSize(400,400);
Panel p=new Panel();
p.setBackground(Color.yellow);
p.setLayout(new GridLayout(2,1));
f.add(p);
p.add(L);
p.add(L1);
L.setSize(100,100);
L.setAlignment(Label.CENTER);
L1.setSize(200,100);
L1.setAlignment(Label.LEFT);
f.setVisible(true);
}}
51
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);
52
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.
54
55
import java.awt.*;
public class TextAreaTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel();
f.add(p1);
String s=“JAVA";
p1.setLayout(new GridLayout(2,1,50,50));
TextField tf=new TextField(s);
p1.add(tf);
f.setVisible(true);
}
}
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.
56
TEXTAREA
Sometimes a single line of text input is not enough for a
given task. To handle these situations, the AWT includes
a simple multiline editor called TextArea.
Following are the constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
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.
58
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);
59
METHODS
TextArea is a subclass of TextComponent.
Therefore, it supports the getText( ), setText( ),
getSelectedText( ), select( ), isEditable( ), and
setEditable( ) methods as of TextField.
TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int
endIndex)
61
import java.awt.*;
public class TextAreaTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel();
f.add(p1);
String s="Welcome \n to \n Advanced \n JAVA";
p1.setLayout(new GridLayout(2,1,50,50));
TextArea ta=new TextArea(s);
p1.add(ta);
f.setVisible(true);
}
}
BUTTONS
The most widely used control is the push button.
A push button is a component that contains a label and
that generates an event when it is pressed.
Push buttons are objects of type Button.
Button defines these two constructors:
Button( )
Button(String str)
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.
64
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);
65
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);
66
EXAMPLE
import java.awt.*;
public class CheckBoxTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel(new GridLayout(2,1,10,10));
f.add(p1);
Checkbox cb2=new Checkbox("ADV. JAVA");
p1.add(cb2);
f.setVisible(true);
}
}
67
import java.awt.*;
public class CheckBoxTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel(new GridLayout(2,1));
f.add(p1);
Checkbox cb1=new Checkbox("CORE JAVA");
Checkbox cb2=new Checkbox("ADV. JAVA");
p1.add(cb1);
p1.add(cb2);
f.setVisible(true);
}
}
68
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.
69
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);
70
import java.awt.*;
public class CheckBoxGroupTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel(new GridLayout(2,1));
f.add(p1);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1=new Checkbox("J2SE",cbg,false);
Checkbox cb2=new Checkbox("J2EE",cbg,true);
Checkbox cb3=new Checkbox("J2ME",cbg,false);
p1.add(cb1);
p1.add(cb2);
p1.add(cb3);
f.setVisible(true);
}
}
71
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:
72
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.
73
import java.awt.*;
public class Choice1 {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel(new GridLayout(2,1));
f.add(p1);
final Choice c=new Choice();
c.add("AAAA");
c.add("BBBB");
c.add("CCCC");
c.add("EEEE");
p1.add(c);
f.setVisible(true);
}
} 74
LISTS
A list is a rectangle containing a series of items:
The user can choose an item by clicking on it:
75
LISTS
If not all list items are visible, a scrollbar appears
to the right of the list:
76
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");
77
import java.awt.*;
public class ListTest {
public static void main(String[] args) {
Frame f = new Frame("Frame Test");
f.setSize(450, 450);
Panel p1=new Panel();
f.add(p1);
List L=new List();
L.add("AAAA");
L.add("BBBB");
L.add("CCCC");
L.add("DDDD");
L.add("EEEE");
p1.add(L);
f.setVisible(true);
}
}
78
EVENT HANDLING
All components can listen for one or more
events.
Typical examples are:
Mouse movements
Mouse clicks
Hitting any key
Hitting return key
etc.
Telling the GUI what to do when a
particular event occurs is the role of the
event handler.
EVENT HANDLING MODEL OF AWT
Event source
Event listener
Event object
Event handling
methods
ACTION EVENTS ON BUTTONS
Button ActionListener
ActionEvent
actionPerformed(..)
CREATING EVENT LISTENERS
90
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.
Practice
Examples
91
12.8 EXAMPLES
The ConvertTemp, ShowDefinition, and
PickColor programs illustrate the use of
various GUI components.
92
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:
93
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:
94
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.
95
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.
96
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.
97
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.
98
ConvertTemp.java
// Converts a Fahrenheit temperature entered by the user to
// Celsius, or vice versa
import java.awt.*;
import java.awt.event.*;
import jpb.*;
// Driver class
public class ConvertTemp {
public static void main(String[] args) {
Frame frame =
new ConvertTempFrame("Temperature Conversion");
frame.setSize(150, 75);
frame.setVisible(true);
}
} 99
// Frame class
class ConvertTempFrame extends Frame {
private TextField fahrenField = new TextField();
private TextField celsiusField = new TextField();
// Constructor
public ConvertTempFrame(String title) {
// Set title for frame and choose layout
super(title);
setLayout(new GridLayout(2, 2));
// Add Fahrenheit label and text field to frame; attach
// listener to text field
add(new Label("Fahrenheit"));
add(fahrenField);
fahrenField.addActionListener(new FahrenheitListener());
100
// 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 + "");
}
}
101
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:
103
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:
104
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.
105
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.
106
ShowDefinition.java
// Shows the definition of a term
import java.awt.*;
import java.awt.event.*;
// Driver class
public class ShowDefinition {
public static void main(String[] args) {
Frame f = new ShowDefinitionFrame("Show Definition");
f.setSize(300, 160);
f.setVisible(true);
}
}
107
// Frame class
class ShowDefinitionFrame extends Frame {
private List termList = new List();
private TextArea definitionArea = new TextArea();
private String[] terms =
{"Button", "Checkbox", "Choice", "Label",
"List", "Scrollbar", "TextArea", "TextField"};
private String[] definitions =
{"A labeled button that can \nbe pressed",
"A box that can be clicked \n\"on\" or \"off\"",
"A menu that displays one \nitem at a time",
"A string that can be \npositioned next to " +
"other\ncomponents",
"A scrolling list of items",
"A sliding bar that can be \neither horizontal or " +
"vertical",
"A multiline area in which \ntext can be displayed " +
"or\nedited",
"A single line of text that \ncan be displayed " +
"or\nedited"};
108
// 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());
}
109
// 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);
}
}
}
110
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.
111
USING LABELS AND SCROLLBARS:
PICKING COLORS
Initially, each scrollbar will be in its middle
position, representing the color gray:
112
USING LABELS AND SCROLLBARS:
PICKING COLORS
By moving the scrollbars, the user can
experiment with different color combinations:
113
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.
114
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.
115
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.
116
PickColor.java
// Allows the user to pick a color by moving three scrollbars
import java.awt.*;
import java.awt.event.*;
// Driver class
public class PickColor {
public static void main(String[] args) {
Frame f = new PickColorFrame("Pick Color");
f.setSize(150, 200);
f.setVisible(true);
}
}
117
// Frame class
class 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));
118
// 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());
}
119
// 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);
}
}
120
// Listener for window
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
}
121