Chapter 7 - GUI
Chapter 7 - GUI
2
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
components,
event-handlingGUIs
Tobuild classes
andandhandle
interfaces.
events by user
generated interactions with GUIs
To handle mouse events and keyboard events.
3
Introduction
A graphical user interface (GUI) presents a user-
friendly
mechanism for interacting with an application.
A GUI gives an application a distinctive “look” and “feel”.
There are different 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
JavaFx(not covered within this course)
4
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 referred to as heavyweight components.
5
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.
6
Java GUI API
The GUI API contains classes that can be classified into
three groups:
component classes,
container classes, and
helper classes.
7
Java GUI API (cont’d)
8
Frames
To create a user interface, you need to create either a
frame or an applet to hold the user-interface
components.
A top-level window (that is, a window that is not
contained 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 and the
title, minimize/maximize(restore-down)/close
buttons),
an optional menu bar and
the content display area.
9
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
} 10
Frame (cont’d)
11
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(JF
rame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
12
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);
13
}
Layout Managers
Java’s layout managers provide a level of abstraction that
automatically 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:
FlowLayout, GridLayout, and BorderLayout.
14
FlowLayout
Flowlayout
Is the simplest layout manager.
The components are arranged in the container from left to right in the
order 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.
15
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);
16
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);
}
}
17
FlowLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
19
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 columns
are nonzero, the number of rows is the dominating
parameter.
All components are given equal size in the container
of GridLayout.
20
GridLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
Output
22
BorderLayout
Divides a container into five areas: East, South,
West,
North, and Center.
Components are added to a BorderLayout using
by add(Component, index), where index is a
constant
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER.
23
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));
24
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_C
LOSE);
frame.setVisible(true);
}
}
Output
25
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
default
a FlowLayout manager or
Panel(LayoutManager) to create a new panel
specified layout manager. with
the
26
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 to hold label and text field; 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); 27
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
SimplePanelExample frame = new SimplePanelExample();
frame.setTitle("Panel With Components");
frame.setSize(350, 100);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
E);
frame.setVisible(true);
}
}
Output:
28
Panels (cont’d)
Example 2
import java.awt.GridLayout;
import javax.swing.*;
import
java.awt.BorderLayout;
30
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
31
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
Component 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 style from Font.PLAIN (0), Font.BOLD (1),
a (2), and Font.BOLD Font.ITALIC (3), and
Font.ITALIC
specify a font size of any positive integer.
32
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);
33
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
represented 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
background and foreground colors.
34
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,
LIGHT_GRAY, BLUE,MAGENTA,
CYAN, DARK_GRAY,
ORANGE, GRAY,
PINK, RED,
GREEN,
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);
35
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);
}
36
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);
}
}
37
Image Icons
import javax.swing.*;
import java.awt.GridLayout;
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));
38
Image Icons (cont’d)
39
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
internal 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-clicking
action event.
The root class of the event classes is java.util.EventObject.
40
Event Handling (cont’d)
The following Table lists external user actions, source objects, and
event types fired
41
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 object,
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.
Registration methods depend on the event type. For ActionEvent,
the method is addActionListener.
42
Example 1
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
44
Example 1(cont’d)
class OKListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}
45
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
49
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);
50
Example 3(cont’d)
add(secondno);
add(equal);
add(result);
add(jbclear);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,100);
setLocationRelativeTo(null);
setVisible(true);
}
51
Example 3(cont’d)
public static void main(String args[]) {
AddNo gui = new AddNo();
}
class AddListenerClass implements
ActionListener{
Integer.valueOf(secondno.getText()).intValue();
}
catch(NumberFormatException ex)
{ JOptionPane.showMessageDialog(null, "Please Enter
Only Number" );
return;
52
}
Example 3(cont’d)
sum = fno + sno;
result.setText(""+sum);
}
else{
firstno.setText("");
secondno.setText("");
result.setText("");
}
} // actionPerformed()
}
}
53
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()
54
Example 4(cont’d)
public static void main(String args[]) {
Converter f = new Converter();
f.setSize(400, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
} // main()
class ConverterHandler implements
ActionListener{
public void
actionPerformed( ActionEvent e )
{
//CHECK TO ACCEPT ONLY
NUMBERS
double miles;
try{
miles =
Double.value
55
Of(input.get
Example 4(cont’d)
display.setText("");
double km = miles/0.62;
display.append(miles + " miles equals " + km + " kilometers\n");
} // actionPerformed()
}//ConvertHandler
}//Converter
56
Exercise
Write a java program to create the following GUI.
1
2
57
Exercise
3
58