Chapter 1
Chapter 1
1
Objectives
In this chapter you will learn:
The design principles of graphical user interfaces
(GUIs).
To create and manipulate buttons, labels, lists, text
fields and panels.
To use layout managers to arrange GUI components
To understand the packages containing GUI compo-
nents, event-handling classes and interfaces.
To build GUIs and handle events generated by user in-
teractions with GUIs
To handle mouse events and keyboard events.
2
Introduction
A graphical user interface (GUI) presents a user-friendly mecha-
nism for interacting with an application.
A GUI gives an application a distinctive “look” and “feel”.
There are two main sets of visual components and containers
for user interface design in JAVA:
AWT (Abstract Window Toolkit) - in package java.awt and
Swing - in package javax.swing
3
AWT vs. Swing
AWT is fine for developing simple graphical user interfaces, but not
for developing comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs.
The AWT user-interface components were replaced by a more robust,
versatile, and flexible library known as Swing components.
Swing components depend less on the target platform and use less of
the native GUI resource.
Swing components are painted directly on canvases using Java code.
For this reason, Swing components that don’t rely on native GUI are
referred to as lightweight components, and AWT components are re-
ferred to as heavyweight components.
4
AWT vs. Swing (cont’d)
AWT features include:
A rich set of user interface components.
A robust event-handling model.
Graphics and imaging tools, including shape, color, and font classes.
Swing features include:
All the features of AWT.
100% Pure Java certified versions of the existing AWT com-
ponent set (Button, Scrollbar, Label, etc.).
A rich set of higher-level components (such as tree view, list
box, and tabbed panes).
Pure Java design, no reliance on peers.
Pluggable Look and Feel.
5
Java GUI API
The GUI API contains classes that can be classified into three
groups:
component classes,
container classes, and
helper classes.
The component classes, such as JButton, JLabel, and JTextField,
are for creating the user interface.
The container classes, such as JFrame, JPanel, and JApplet, are
used to contain other components.
The helper classes, such as Graphics, Color, Font, FontMetrics,
and Dimension, are used to support GUI components.
6
Java GUI API (cont’d)
7
Java GUI API (cont’d)
Class Object is the super class of the Java class hierarchy.
Component is the root class of all the user-interface classes in-
cluding container classes.
JComponent is the root class of all the lightweight Swing com-
ponents.
An instance of Container can hold instances of Component.
Window, Panel, Applet, Frame, and Dialog are the container
classes for AWT components.
To work with Swing components, use Container, JFrame, JDia-
log, JApplet, and Jpanel.
8
Java GUI API (cnt’d)
9
Frames
To create a user interface, you need to create either a
frame or an applet to hold the user-interface compo-
nents.
A top-level window (that is, a window that is not con-
tained inside another window) is called a frame in
Java.
To create a frame, use the JFrame class
A Frame has:
a title bar (containing an icon, a title, and the mini-
mize/maximize(restore-down)/close buttons),
an optional menu bar and
the content display area.
10
Frame
Example 1
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("MyFrame");
frame.setSize(400, 300); // Set the frame size
// Center a frame
frame.setLocationRelativeTo(null); //or .setLocation(300,200)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
}
}
11
Frame (cont’d)
12
Frame (cont’d)
Adding Components to a Frame
Example 1: Adding button
import javax.swing.JFrame;
import javax.swing.JButton;
public class FrameWithButton {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a button into the frame
JButton jbtOK = new JButton("OK");
frame.add(jbtOK);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
13
Frame (cont’d)
Example 2: Adding Lablel
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FrameWithLabel {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
// Add a lable into the frame
JLabel jLblName = new JLabel(“First Name");
frame.add(jLblName);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
14
Layout Managers
Java’s layout managers provide a level of abstraction that auto-
matically maps your user interface on all window systems.
The Java GUI components are placed in containers, where they
are arranged by the container’s layout manager.
Layout managers are set in containers using the
setLayout(aLayoutManager) method.
This section introduces three basic layout managers: FlowLay-
out, GridLayout, and BorderLayout.
15
FlowLayout
Flowlayout
Is the simplest layout manager.
The components are arranged in the container from left to right in the or-
der in which they were added. When one row is filled, a new row is started.
You can specify the way the components are aligned by using one of three
constants:
FlowLayout.RIGHT,
FlowLayout.CENTER, or
FlowLayout.LEFT.
You can also specify the gap between components in pixels.
16
FlowLayout (cont’d)
Example
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout{
public static void main(String args[]){
JFrame frame = new JFrame();
//Set FlowLayout, aligned left with horizontal gap 10
//and vertical gap 20 between components
FlowLayout x = new FlowLayout(FlowLayout.LEFT, 10, 20);
frame.setLayout(x);
//Add labels and text fields to the frame
JLabel jlblFN = new JLabel("First Name");
JTextField jtxtFN = new JTextField(8);
JLabel jlblMI = new JLabel("MI");
JTextField jtxtMI = new JTextField(1);
JLabel jlblLN = new JLabel("Last Name");
JTextField jtxtLN = new JTextField(8);
17
FlowLayout (cont’d)
frame.add(jlblFN);
frame.add(jtxtFN);
frame.add(jlblMI);
frame.add(jtxtMI);
frame.add(jlblLN);
frame.add(jtxtLN);
frame.setTitle("ShowFlowLayout");
frame.setSize(220, 150);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
18
FlowLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
19
FlowLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
20
GridLayout
Arranges components in a grid (matrix) formation.
The components are placed in the grid from left to
right, starting with the first row, then the second, and
so on, in the order in which they are added.
If both the number of rows and the number of col-
umns are nonzero, the number of rows is the dominat-
ing parameter.
All components are given equal size in the container
of GridLayout.
21
GridLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
// Set GridLayout, 3 rows, 2 columns, and gaps 5 between
// components horizontally and vertically
setLayout(new GridLayout(3, 2, 5, 5));
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(8));
add(new JLabel("Last Name"));
add(new JTextField(8));
}
22
GridLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
23
BorderLayout
Divides a container into five areas: East, South, West, North, and
Center.
Components are added to a BorderLayout by using
add(Component, index), where index is a constant
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER.
24
BorderLayout
EXAMPLE
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame
{
public ShowBorderLayout() {
// Set BorderLayout with horizontal gap 5 and vertical gap 10
setLayout( new BorderLayout(5, 10));
// Add buttons to the frame
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
25
BorderLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
26
Panels
With Java GUI programming, you can divide a window
into panels.
Panels act as subcontainers to group user-interface
components.
You add the buttons in one panel, then add the panel
into the frame.
You can use new JPanel() to create a panel with a de-
fault FlowLayout manager or new
Panel(LayoutManager) to create a panel with the
specified layout manager.
27
Panels (cont’d)
Example 1
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class SimplePanelExample extends JFrame {
public SimplePanelExample() {
// Create panel p1 for the buttons and set GridLayout
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 2));
//Add label and text field to the panel
p1.add(new JLabel("First Name"));
p1.add(new JTextField(8));
// Create panel p2 to hold p1 and some other component
JPanel p2 = new JPanel(new BorderLayout());
p2.add(p1, BorderLayout.NORTH);
p2.add (new JButton("Button in Panel 2"), BorderLayout.SOUTH);
// add contents into the frame
add(p2);
}
28
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
SimplePanelExample frame = new SimplePanelExample();
frame.setTitle("Panel With Components");
frame.setSize(300, 100);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
29
Panels (cont’d)
Example 2
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.BorderLayout;
30
Panels (cont’d)
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));
31
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
32
The Font Class
You can create a font using the java.awt.Font class and set fonts
for the components using the setFont method in the Compo-
nent class.
The constructor for Font is:
Font(String name, int style, int size);
You can choose a font name from SansSerif, Serif, Monospaced,
Dialog, or DialogInput,
Choose a style from Font.PLAIN (0), Font.BOLD (1), Font.ITALIC
(2), and Font.BOLD Font.ITALIC (3), and specify a font size of any
positive integer.
33
Font (cont’d)
Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC,
12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);
34
The Color Class
You can set colors for GUI components by using the java.awt.-
Color class.
Colors are made of red, green, and blue components, each rep-
resented by an int value that describes its intensity, ranging
from 0 (darkest shade) to 255 (lightest shade).
You can create a color using the following constructor:
public Color(int r, int g, int b);
Example:
Color color = new Color(128, 100, 100);
You can use the setBackground(Color c) and
setForeground(Color c) methods to set a component’s back-
ground and foreground colors.
35
The Color Class (cont’d)
Example
JButton jbtOK = new JButton("OK");
jbtOK.setBackground(color);
jbtOK.setForeground(new Color(100, 1, 1));
Alternatively, you can use one of the 13 standard colors (BLACK,
BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MA-
GENTA, ORANGE, PINK, RED, WHITE, and YELLOW) defined as
constants in java.awt.Color.
The following code, for instance, sets the foreground color of a
button to red:
jbtOK.setForeground(Color.RED);
36
The Color Class (cont’d)
Example
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.*;
public class ColorExample extends JFrame{
public ColorExample(){
JFrame jf = new JFrame("Color Frame");
setLayout(new GridLayout(1,2));
Color color = new Color(128, 100, 100);
JButton bcleft = new JButton("Left Button");
JButton bcright = new JButton("Right Button");
bcleft.setBackground(color);
bcright.setForeground(new Color(250,0, 0)); //
bc2.setForeground(Color.RED);
add(bcleft);
add(bcright);
}
37
The Color Class (cont’d)
public static void main(String[] args){
ColorExample ce = new ColorExample();
ce.setSize(300,150);
ce.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ce.setLocationRelativeTo(null);
ce.setVisible(true);
}
}
38
Image Icons
import javax.swing.*;
import java.awt.*;
public class ImageExample extends JFrame {
public ImageExample() {
ImageIcon homeIcon = new ImageIcon("src/home.gif");
ImageIcon birdIcon = new ImageIcon("src/bird.gif");
ImageIcon mailIcon = new ImageIcon("src/mail.gif");
setLayout(new GridLayout(1, 3, 5, 5));
add(new JLabel(homeIcon));
add(new JButton(birdIcon));
add(new JLabel(mailIcon));
39
Image Icons (cont’d)
/** Main method */
public static void main(String[] args) {
ImageExample frame = new ImageExample();
frame.setTitle("TestImageIcon");
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
SE);
frame.setVisible(true);
}
}
40
Event Handling
Event and Event Source
When you run a Java GUI program, the program interacts
with the user, and the events drive its execution.
An event can be defined as a signal to the program that
something has happened.
Events are triggered either by external user actions, such as
mouse movements, button clicks, and keystrokes, or by in-
ternal program activities, such as a timer.
The program can choose to respond to or ignore an event.
The component that creates an event and fires it is called
the source object or source component.
For example, a button is the source object for a button-click-
ing action event.
The root class of the event classes is java.util.EventObject.
41
Event Handling (cont’d)
The following Table lists external user actions, source objects, and
event types fired
42
Event Handling (cont’d)
Listeners, Registrations, and Handling Events
Java uses a delegation-based model for event handling:
a source object fires an event, and an object interested in the
event handles it. The latter object is called a listener.
For an object to be a listener for an event on a source ob-
ject, two things are needed:
The listener object must be an instance of the corresponding
event-listener interface
to ensure that the listener has the correct method for processing the
event. The following table
lists event types, the corresponding listener interfaces, and the
methods defined in the listener interfaces.
The listener object must be registered by the source object. Reg-
istration methods depend on the event type. For ActionEvent, the
method is addActionListener.
43
Event Handling (cont’d)
Example 1
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HandleEvent extends JFrame{
public HandleEvent() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);
add(panel); // Add panel to the frame
44
Event Handling (cont’d)
// Register listeners
OKListenerClass listener1 = new OKListenerClass();
CancelListenerClass listener2 = new CancelListenerClass();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2);
}
45
Event Handling (cont’d)
class OKListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}
46
Event Handling (cont’d)
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyGUI extends JFrame {
public JButton clickme = new JButton("ClickMe");
public JButton tests = new JButton("Test");
public MyGUI() {
// Add clickme to the GUI and assign it a listener
setLayout(new GridLayout(2, 1, 5, 5));
add(clickme);
add(tests);
ClickListenerClass clicklistener = new ClickListenerClass();
clickme.addActionListener(clicklistener);
47
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,200);
setVisible(true);
}
public static void main(String args[]) {
MyGUI gui = new MyGUI();
}
class ClickListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clickme) {
tests.setText("Clickme button clicked");
}
} // actionPerformed()
}
} // MyGUI class
48
Event Handling (cont’d)
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyGUI extends JFrame
implements ActionListener {
private JButton clickme = new JButton("ClickMe");
private JButton tests = new JButton("Test");
public MyGUI() {
// Add clickme to the GUI and assign it a listener
setLayout(new GridLayout(2, 0, 5, 5));
add(clickme);
add(tests);
clickme.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
setVisible(true);
}
49
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clickme) {
tests.setText("Clickme button clicked");
}
} // actionPerformed()
50
Example 3: Add two numbers
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddNo extends JFrame {
private JTextField firstno = new JTextField(4);
private JLabel plus = new JLabel("+");
private JTextField secondno = new JTextField(4);
private JButton equal = new JButton("=");
private JTextField result = new JTextField(4);
private JButton jbclear = new JButton("Clear");
public AddNo() {
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
add(firstno);
add(plus);
51
add(secondno);
add(equal);
add(result);
add(jbclear);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,100);
setLocationRelativeTo(null);
setVisible(true);
}
52
public static void main(String args[]) {
AddNo gui = new AddNo();
}
class AddListenerClass implements ActionListener{
Number" );
return;
}
53
sum = fno + sno;
result.setText(""+sum);
}
else{
firstno.setText("");
secondno.setText("");
result.setText("");
}
} // actionPerformed()
}
} // MyGUI class
54
Example 4
import javax.swing.*; // Packages used
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener{
private JLabel prompt = new JLabel("Distance in miles: ");
private JTextField input = new JTextField(6);
private JTextArea display = new JTextArea(10,20);
private JButton convert = new JButton("Convert!");
public Converter() {
setLayout(new FlowLayout());
add(prompt);
add(input);
add(convert);
add(display);
display.setLineWrap(true);
display.setEditable(false);
ConverterHandler ch = new ConverterHandler();
convert.addActionListener(ch);
} // Converter()
55
public static void main(String args[]) {
Converter f = new Converter();
f.setSize(400, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // main()
class ConverterHandler implements ActionListener{
public void actionPerformed( ActionEvent e ) {
//CHECK TO ACCEPT ONLY NUMBERS
double miles;
try{
miles = Double.valueOf(input.getText()).doubleValue();
}
catch ( NumberFormatException ex )
{
JOptionPane.showMessageDialog(null, "Please Enter Only Num-
ber" );
return;
} // end catch
56
display.setText("");
double km = miles/0.62;
display.append(miles + " miles equals " + km + " kilometers\n");
} // actionPerformed()
}//ConvertHandler
}//Converter
57
Inner Class
An inner class, or nested class, is a class defined
within the scope of another class.
Example:
58
Inner Class (cont’d)
Define a class an inner class if it is used only by its
outer class.
An inner class is compiled into a class named Outer-
ClassName$InnerClassName.class. For example, the
inner class OKListenerClassInner in HandleEventIn-
ner is compiled into
HandleEventInner$OKListenerClassInner.class.
Use of inner classes is to combine dependent classes
into a primary class. This reduces the number of
source files.
59
Inner Class(cont’d)
Example: HandleEvent using inner class
import javax.swing.*
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HandleEventInner extends JFrame{
public HandleEventInner() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);
add(panel); // Add panel to the frame
// Register listeners
OKListenerClassInner listener1 = new OKListenerClassInner();
CancelListenerClassInner listener2 = new CancelListenerClassInner();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2);
}
60
Inner class (cont’d)
public static void main(String[] args) {
HandleEventInner frame = new HandleEventInner();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//Inner class: Ok
class OKListenerClassInner implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked!");
}
}
//Inner class: cancel
class CancelListenerClassInner implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Cancel button clicked!");
}
}
}
61
Anonymous classes
A listener class is designed specifically to create a listener ob-
ject for a GUI component (e.g., a button).
The listener class will not be shared by other applications and
therefore is appropriate to be defined inside the frame class as
an inner class.
Inner-class listeners can be shortened using anonymous inner
classes.
An anonymous inner class is an inner class without a name.
It combines defining an inner class and creating an instance of
the class in one step.
An anonymous inner class is compiled into a class named Out-
erClassName$n.class. For example, if the outer class Test has
two anonymous inner classes, they are compiled into
Test$1.class and Test$2.class.
62
63
Anonymous class (cont’d)
Example: HandleEventAnonymous
import…
public class HandleEventAnonymous extends JFrame{
public HandleEventAnonymous() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
// Create a panel to hold buttons
JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);
add(panel); // Add panel to the frame
// Register listeners
jbtOK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked!");
}
});
64
Anonymous class (cont’d)
jbtCancel.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Cancel button clicked!");
}
});
}
public static void main(String[] args) {
HandleEventAnonymous frame = new HandleEventAnonymous();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
65
More Examples
CheckBoxFrame.java
Text Field: TextFieldDemo.java
Combo box: ComboBoxDemo.java
Mouse event: MoveMessageDemo.java
Key event: KeyEventDemo.java
Timer: AppendTimer.java
66
extends JFrame
Three reasons:
Creating a GUI application means creating a frame, so it
is natural to define a frame to extend JFrame.
The frame may be further extended to add new compo-
nents or functions.
The class can be easily reused. For example, you can
create multiple frames by creating multiple instances of
the class.
67