Graphical User Interfaces
• Users interact with a program through a graphical
user interface (GUI).
• Java provides strong support for building GUIs
through the java.awt package
• Chapter 9 focuses on:
–
–
–
–
GUI components
event-driven programming
containers and component hierarchies
layout managers
1
GUI Elements
• The key elements of a Java graphical user interface
– GUI components
– Events and Listeners
– Layout managers
• GUI components
– text fields and buttons,
– the screen elements that a user manipulates with the
mouse and keyboard
2
GUI Elements
• Events and Listener
– Events signal important user actions, like a mouse click
– Listener handle events from a component
• Layout managers
– govern how the components appear on the screen
3
Event-Driven Programming
• Programs with GUIs must respond to events,
generated by GUI components, that indicate that
specific actions have occurred
• Listeners wait for events to occur
– Listeners are a special category of classes.
• Therefore, a GUI program is composed of:
– the code that presents the GUI to the user
– the listeners that wait for events to occur
– the specific code that is executed when events occur
4
Event-Driven Programming
• Listener interface defined for each event type
– Each listener interface contains the abstract methods
required to respond to specific events
– A listener class implements a particular listener interface
• Listeners are "added" to a particular GUI component
• When a component generates an event, the method
corresponding to that event is executed in the listener
• See Mimic.java
5
The GUI Program Model
Listeners
Handle events
Add listeners
GUI
Event effects
Programspecific
6
Event Interfaces
• Multiple listeners can be added to a component
Listener1
GUI Component
Listener2
• Multiple components can be processed by the
same listener
GUI Component 1
Listener1
GUI Component 2
7
GUI Components
• There are several GUI components that permit
specific kinds of user interaction:
–
–
–
–
–
–
labels
text fields
text areas
lists
buttons
scrollbars
8
Labels
• A label defines a line of text displayed on a GUI
• Labels are static
– they cannot be selected or modified by the human user
once added to a container
• A label is instantiated from the Label class
• The Label class contains
– several constructors and methods for setting up and
modifying a label's content and alignment
9
Text Fields and Text Areas
• A text field
– displays a single line of text in a GUI
– It can be made editable, and
– provide a means to get input from the user
• A text area
– is similar to text field,
– but displays multiple lines of text
• They are defined by the TextField and TextArea
classes
10
Example : Fahrenheit
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Fahrenheit extends Applet {
private Label title = new Label ("Fahrenheit to Celcius Converter");
private Label question = new Label ("Enter Fahrenheit:");
private Label answer = new Label ("Temperature in Celcius:");
private
private
private
private
TextField fahrenheit = new TextField (5);
Label celcius = new Label ("N/A");
TextArea log = new TextArea (5, 20);
Fahrenheit_Listener listener =
new Fahrenheit_Listener (this);
11
public void init() {
fahrenheit.addActionListener (listener);
log.setEditable (false);
add (title);
add (question);
add (answer);
add (celcius);
resize (200,200);
} // method init
add (fahrenheit);
add (log);
public void convert() {
int fahrenheit_temperature, celcius_temperature;
String text = fahrenheit.getText();
fahrenheit_temperature = Integer.parseInt (text);
celcius_temperature = (fahrenheit_temperature-32)*5/9;
celcius.setText (Integer.toString (celcius_temperature));
log.append (text + " converts to " + celcius.getText() + "\n");
} // method convert
} // class Fahrenheit
12
class Fahrenheit_Listener implements ActionListener {
private Fahrenheit applet;
public Fahrenheit_Listener (Fahrenheit listening_applet) {
applet = listening_applet;
} // constructor Fahrenheit_Listener
public void actionPerformed(ActionEvent action) {
applet.convert();
} // method actionPerformed
} // class Fahrenheit_Listener
13
Lists
• A list
– display a list of selectable strings
– can contain any number of strings and
– can be instantiated to allow multiple selections within it
• The size of the list
– the number of visible rows or strings within it
• A list is defined by the List class
14
Buttons
• The java.awt package supports four distinct types of
buttons:
–
–
–
–
Push buttons
Choice Buttons
Checkbox buttons
Radio buttons
• Each button type serves a particular purpose
15
Push Button
• A push button
– a single button which can be created with or without a
label
– when a push button is pressed, a particular action occurs
• It is defined by the Button class
16
Example: ButtonDemo.java
import java.awt.*;
import java.applet.Applet;
public class ButtonDemo extends Applet {
Button b1,b2,b3;
public void init( ) {
b1 = new Button( );
b1.setLabel("Disable middle button");
b2 = new Button("Middle button");
b3 = new Button("Enable Middle button");
add(b1);
add(b2);
add(b3);
setVisible(true);
}
17
Example: ButtonDemo.java
public boolean action(Event e, Object arg) {
Object target = e.target;
if (target == b1) {
b2.disable( );
b1.disable( );
b3.enable( );
return true;
}
if (target == b3) {
b2.enable( );
b1.enable( );
b3.disable( );
return true;
}
return false;
}
}
18
The action method.
• The action method is an especially important
event-handling method.
• Basic components produce action events
–
–
–
–
–
Button
Checkbox
Choice
List
TextField
public boolean action(Event e, Object arg) {
…
}
19
Other methods for event handling
• mouseEnter(Event.MOUSE_ENTER)
• mouseExit(Event.MOUSE_EXIT)
• mouseMove(Event.MOUSE_MOVE)
• mouseDown(Event.MOUSE_DOWN)
• mouseDrag(Event.MOUSE_DRAG)
• mouseUp(Event.MOUSE_UP)
• keyDown(Event.KEY_PRESS or Event.KEY_ACTION)
• keyDown(Event.KEY_RELEASE or Event.KEY_ACTION)
• handleEvent(all event types)
20
Choice button
• A choice button is a single button which displays a
list of choices when pushed
• The user can then scroll through and choose the
appropriate option
• It is defined by the Choice class
21
Example: ChoiceDemo.java
import java.awt.*;
import java.applet.Applet;
public class ChoiceDemo extends Applet {
Choice choice;
Label label;
public void init(){
choice = new Choice( );
choice.addItem("hana");
choice.addItem("dul");
choice.addItem("set");
choice.addItem("넷");
label = new Label( );
setLabelText(choice.getSelectedIndex( ),
choice.getSelectedItem( ));
add(choice);
add(label);
}
22
Example: ChoiceDemo.java
void setLabelText(int num, String text) {
label.setText("Item #" + num + " selected" + "Text = \"" +
text + "\".");
}
public boolean action(Event e, Object arg) {
if (e.target instanceof Choice) {
setLabelText(choice.getSelectedIndex( ), (String) arg);
return true;
}
return false;
}
}
23
Scrollbars
• A scrollbar is a slider that indicates a relative
position or quantity
• They are automatic on text areas and list
components, but can be used independently
• The position of the slider in the range corresponds
to a particular numeric value in a range associated
with the scrollbar
• A scrollbar is defined by the Scrollbar class
• See Zoom.java
24
Example: Zoom.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Zoom extends Applet {
private final int SIZE = 300;
private Scrollbar bar =
new Scrollbar(Scrollbar.HORIZONTAL, 10, 64, 10, SIZE);
private Zoom_Listener listener = new Zoom_Listener (this);
private int current_size = 10;
private Image picture;
25
public void init() {
setLayout (new BorderLayout());
setBackground (Color.white);
bar.addAdjustmentListener (listener);
picture = getImage (getDocumentBase(), "owl.gif");
add (bar, "South");
setSize (SIZE, SIZE);
setVisible (true);
} // method init
public void zoom_image (int size) {
current_size = size;
repaint();
} // method zoom_image
public void paint (Graphics page) {
page.drawImage (picture, SIZE/2-current_size/2,
SIZE/2-current_size/2, current_size, current_size, this);
} // method draw
} // class Zoom
26
class Zoom_Listener implements AdjustmentListener {
private Zoom applet;
public Zoom_Listener (Zoom zoom_applet) {
applet = zoom_applet;
} // constructor Zoom_Listener
public void adjustmentValueChanged (AdjustmentEvent event)
{
applet.zoom_image (event.getValue());
} // method adjustmentValueChanged
} // class Zoom_Listner
27
Containers
• A container
– A special category of GUI components that group other
components
– All containers are components,
– but not all components are containers
• An applet is a container
– buttons, text fields, and other components can be added to
an applet to be displayed
• Layout manager
– Each container has an layout manager to control the way
components in it are displayed
28
Container vs Components
Container
Button
Component2
TextField
Component1
Component3 Container
29
Containers
• Some containers must be attached to another
graphical surface:
– panel
– applet
• An applet is attached to a browser or appletviewer
window
• Other containers can be moved independently:
– window
– frame
– dialog
30
Containers
Component
Container
Window
Panel
Applet
Frame
Dialog
31
Component Hierarchies
• A GUI is created when containers and other
components are put together
• Component hierarchy
– The relationships between these components
– For example, an applet can contain panels which contain
other panels which contain buttons, etc.
• See Rings_Display.java
32
Checkbox button
• A checkbox button can be toggled on or off
• If used in a group, more than one option can be
chosen at any one time
• Defined by the Checkbox class
33
Radio buttons
• A radio button, like a checkbox button, is toggled on
or off
• Radio buttons must be grouped into a set, and only
one button can be selected at any one time
• They are used to select among a set of mutually
exclusive options
• Radio button sets are defined by the Checkbox and
CheckboxGroup classes
34
Example: CheckboxDemo.java
import java.awt.*;
import java.applet.Applet;
public class CheckboxDemo extends Applet {
public void init( ) {
Panel p1, p2;
Checkbox cb1, cb2, cb3;
Checkbox cb4, cb5, cb6;
cb1 = new Checkbox( );
cb1.setLabel("Checkbox 1");
cb2 = new Checkbox("Checkbox 2");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true);
p1 = new Panel( );
p1.setLayout(new FlowLayout( ));
p1.add(cb1);
p1.add(cb2);
p1.add(cb3);
35
Example: CheckboxDemo.java
CheckboxGroup cbg = new CheckboxGroup( );
cb4 = new Checkbox("Checkbox 4", cbg, false);
cb5 = new Checkbox("Checkbox 5", cbg, false);
cb6 = new Checkbox("Checkbox 6", cbg, false);
p2 = new Panel( );
p1.setLayout(new FlowLayout( ));
p2.add(cb4);
p2.add(cb5);
p2.add(cb6);
setLayout(new GridLayout(0, 2));
add(p1);
add(p2);
}
}
36
Layout Managers
• There are five predefined layout managers in the
java.awt package:
–
–
–
–
–
flow layout
border layout
card layout
grid layout
grid bag layout
• Each container has a particular layout manager
associated with it by default
• A programmer can also create custom layout
managers
37
Flow Layout
• Flow layout
– Components are placed in a row from left to right in the order
in which they are added
– A new row is started when no more components can fit in the
current row
– The components are centered in each row by default
• The programmer can specify the size of both the
vertical and horizontal gaps between the components
• Flow layout is the default layout for panels and
applets
• See Flow.java
38
Example: Flow.java
import java.applet.Applet;
import java.awt.*;
public class Flow extends Applet {
private Button button1 = new Button ("I");
private Button button2 = new Button ("think");
private Button button3 = new Button ("therefore");
private Button button4 = new Button ("I");
private Button button5 = new Button ("am");
public void init() {
setLayout (new FlowLayout());
add (button1);
add (button2); add (button3);
add (button4);
add (button5); setVisible(true);
} // method init
} // class Flow
39
Grid Layout
• Components are placed in a grid with a userspecified number of columns and rows
• Each component occupies exactly one grid cell
• Grid cells are filled left to right and top to bottom
• All cells in the grid are the same size
• See Grid.java
40
Example: Grid.java
import java.applet.Applet;
import java.awt.*;
public class Grid extends Applet {
private Button button1 = new Button ("I");
private Button button2 = new Button ("think");
private Button button3 = new Button ("therefore");
private Button button4 = new Button ("I");
private Button button5 = new Button ("am");
public void init() {
setLayout (new GridLayout(2,3));
add (button1);
add (button2); add (button3);
add (button4);
add (button5); setVisible(true);
} // method init
} // class Flow
41
Border Layout
• Defines five locations each of which a component
or components can be added
– North, South, East, West, and Center
• The programmer specifies the area in which a
component should appear
• The relative dimensions of the areas are governed
by the size of the components added to them
• See Border.java
42
Example: Border.java
import java.applet.Applet;
import java.awt.*;
public class Border extends Applet {
private Button button1 = new Button ("I");
private Button button2 = new Button ("think");
private Button button3 = new Button ("therefore");
private Button button4 = new Button ("I");
private Button button5 = new Button ("am");
public void init() {
setLayout (new BorderLayout());
add (button1, "North");
add (button2, "South");
add (button3, "East");
add (button4, "West");
add (button5, "Center");
} // method init
} // class Flow
43
Border Layout
North
West
Center
East
South
44
Card Layout
• Components are "stacked" such that only one
component is displayed on the screen
• Components are ordered according to the order in
which they were added to the container
• Methods control which component is currently
visible in the container
• See Card.java
45
Example: Card.java
import java.applet.Applet;
import java.awt.*;
public class Card extends Applet {
private Button button1 = new Button ("I");
private Button button2 = new Button ("think");
private Button button3 = new Button ("therefore");
private Button button4 = new Button ("I");
private Button button5 = new Button ("am");
private CardLayout layout = new CardLayout();
public void init() {
setLayout (layout);
add (button1, "One");
add (button2, "Two");
add (button3, "Three");
add (button4, "Four");
add (button5, "Five");
} // method init
46
Example: Card.java
public void start() {
for (int cards = 1; cards < 50; cards++) {
layout.next(this);
for (int pause = 1; pause < 400000; pause++);
}
} // method start
} // class Card
47
GUI Design
• Careful design of a graphical user interface is key
to a viable software system
• To the user, the user interface is the system
• For each situation, consider which components are
best suited and how they should best be arranged
• See Quotes.java
48
© Copyright 2026 Paperzz