Lesson 12
Graphical User Interface
By the end of this lesson you will learn:
What is Graphical User Interface?
Components of a GUI
Java Library Classes for making a GUI
Customizing the color and font of a GUI component
Different EventListeners
Steps to design a GUI
Designing a GUI
It is obvious that in real life there is a very little usage of console based applications rather
than applications that has graphical components to work with. In this lesson, we will be
learning about how to design a graphical user interface.
What is Graphical User Interface?
A user interface is the medium that a user uses while interacting with a system. The
programs we have done so far are called Console Applications as console is the interface
that the user is interacting with. User is giving input in the console and also getting the
output in the console.
A user interface that uses different graphical components for users to interact with the
system is known as a Graphical User Interface. Example:
The application you are using to read this document is a GUI based application and
anything that you can click here is a GUI component.
The text editor you use while coding is also a GUI based application and even when
you are typing, you are typing in a GUI component.
A GUI makes a user interface more attractive and easier to work with. We can even
customize GUI components to make it better. If GUI was not here, using a computer would
have become boring and irritating.
Components of GUI
There are numerous GUI components. These components can be used to develop a GUI
as per requirements. Some basic and frequently used GUI components are:
Name of Component General Purpose
Label View plain text
TextField Type anything as Text
PasswordField Type anything as Password
Button Trigger any event or to navigate
Radio Button Select any Option
Check Box Select Multiple Options
Button Group Grouping Multiple Radio Buttons or Check Boxes
Drop Down List View items as a list and select one from the list
Text Area Type anything as Text in a large area
Image View an Image
Table View Data in a Table
Panel Create a panel
Frame Design a GUI
Notification/Message Box Display any notification or Message.
The following images show some of the components of a Graphical User Interface:
Label
TextField
PasswordField
Button
Frame
Drop Down List
Radio Buttons
Check Boxes
Java Library Classes for Making a GUI
All the above mentioned GUI components can be created using java library classes. These
classes are inside [Link] package. The following table shows the java library classes
for each pf the above mentioned GUI components:
Name of Component Java Library Class Name
Label JLabel
TextField JTextField
PasswordField JPasswordField
Button JButton
Radio Button JRadioButton
Check Box JCheckBox
Button Group ButtonGroup
Drop Down List JComboBox
Text Area JTextArea
Image ImageIcon
Table JTable
Panel JPanel
Frame JFrame
Notification/Message Box JOptionPane
For example: to create a GUI, we need to write a class that inherits the java library class
JFrame.
Customizing Color and Font
Up until now, we have discussed about the components of a GUI. By default, they do not
have any color. To make a GUI more attractive and eye catching color and font of GUI
components can be customized/changed by using the following library classes:
Color
Font
Both of these classes are in [Link] package. These classes have constructors to create
color and font according to user preference. These user defined colors and fonts can be
used for GUI components by calling library methods of their respective classes. The
following table summarizes some of the necessary constructors and methods of the Color
and the Font class:
Constructors and Methods Description
Creates a color having the RGB value as per
Color(int r, int g, int b)
the parameters
Changes the background color as per the Color
setBackground(Color c)
object passed in the parameter
Changes the font color as per the Color object
setForeground(Color c)
passed in the parameter
Creates a font having the name, style and size
Font(String name, int style, int size)
as per the parameter values
Changes the font as per the Font object passed
setFont(Font f)
in the parameter
Different EventListeners
Now that we know about the things required to design a GUI, we need to know how we
can make a GUI work. All the GUI components can trigger events if they are associated
with an EventListener for respective events. These event listeners invoke respective
methods whenever an event occurs for a component. The following four are some of the
most frequently used event listeners:
ActonListener
MouseListener
KeyListener
FocusListener
All of these listeners are java library interfaces. They are inside the [Link]
package. Each type of listener handles their own type of event.
EventListener Event
ActionListener ActionEvent
MouseListener MouseEvent
KeyListener KeyEvent
FocusListener FocusEvent
A frame that wants to perform some operation or task whenever any event occurs, needs
to implement the respective EventListeners. As these event listeners are interfaces, our
class has to override the all the abstract methods of the implemented interfaces.
The followings are the abstract methods that these interfaces have:
MouseListener
mouseClicked(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)
mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
ActionListener
actionPerformed(ActionEvent ae)
KeyListener
keyTyped(KeyEvent ke)
keyPressed(KeyEvent ke)
keyReleased(KeyEvent ke)
FocusListener
focusGained(FocusEvent fe)
focusLost(FocusEvent fe)
Steps to Design a GUI
As stated earlier, we need to write a class to develop a GUI. The object of our class will
be the GUI. It will be easier to develop a GUI, if we do the followings first:
Draw a sketch of the GUI in a paper.
Make a list of the components of the GUI.
Make a list of color and fonts that the components will have (optional).
Make a list of events that might happen in the GUI.
Now, we can write our class. The followings steps should be followed while writing the
class:
Step 0: Import necessary library classes.
Step 1: Our class needs to extend the JFrame class and implement necessary listeners.
Step 2: The components used in the GUI will be the attributes of our class.
Step 3: The colors and fonts used in the GUI should also be in the attributes (optional).
Step 4: Write a constructor for the class. The body of the constructor can be divided into
several parts:
(a) Initialize the Frame Header, the size of the frame.
(b) Create the panel object and set its layout as null.
(c) Initialize custom Color and Font (Optional).
(d) For each of the components (except for ImageIcon, JTable, ButtonGroup and
JComboBox) follow the pattern of “Three Statements”.
[1] Create an object for the component.
[2] Initialize its size and position.
[3] Add the component in the panel.
(e) Change color and font for the components and add necessary EventListeners
(optional).
(f) Add the panel in the frame.
Step 5: Override the abstract methods of the implemented event listener interfaces.
Step 6: Write a main method in a separate class to display the GUI.
Designing a GUI
Let us assume that we going to develop the following GUI:
Now, let us make a list of the components for this GUI. There are 2 Labels, 1 Text Field, 1
Password Field, 2 Buttons, 2 Radio Buttons, 2 Check Boxes and a 1 Drop Down List. The
color of the “Next” button is Green and the “Exit” button is Red. One of the Label is Blue
in color. The font color of both of the buttons is White. The background color of the GUI
and the font of the Labels are customized. When we click on the Next button, a new GUI
will appear with all the values from the components of this GUI and when the Exit Button
is clicked the program will terminate.
Before starting to code, let us get familiarized with some constructors and methods that
we will be using.
Constructor Description
It creates an object of JLabel. The String text passed in the
public JLabel(String text)
parameter is the text of the label.
public JTextField( ) It creates an object of JTextField.
public JPasswordField( ) It creates an object of JPasswordField.
It creates an object of JButton. The String text passed in
public JButton(String text)
the parameter is the text of the Button.
It creates an object of JRadioButton. The String text
public JRadioButton(String text)
passed in the parameter is the text of the RadioButton.
It creates an object of JCheckBox. The String text passed
public JCheckBox(String text)
in the parameter is the text of the CheckBox.
It creates an object of JComboBox. The value of each
public JComboBox(String [ ]items) index of the String array items passed in the parameter,
represents each value of the Drop Down List.
public JPanel( ) It creates an object of JPanel.
It creates an object of JFrame. We will not be using this
public JFrame(String text)
one directly.
Method Description
It is called to initialize the size of the frame.
void setSize(int length, int height) Length and height specifies the length and
height of the Frame respectively.
It is called to make the “X” button to close the
void setDefaultCloseOperation(int value)
program.
It is called to specify the layout to follow while
void setLayout(LayoutManager lm)
adding a component into a panel.
It is called to initialize the position and size of a
GUI component. The parameter values specifies
the x coordinate of the upper left corner of the
void setBounds(int upLeftX, int upLeftY, int
component, the y coordinate of the upper left
length, int height)
corner of the component, the length of the
component and the height of the component
respectively.
Component add(Component c) It is called to add a component to a container.
It is called to get the text of the component for
String getActionCommand( )
which an action event has occurred.
It is called to initialize/change the text of a
void setText(String text)
component.
String getText( ) It is called to get the text of any component.
It is called to check whether a RadioButton or a
boolean isSelected( )
CheckBox is selected or not.
It is called to get the item which has been
selected from a ComboBox. This method does
Object getSelectedItem( ) not return the text of the item. To get the text of
the item, we need to call another method
toString( ) with this method.
In order to change the background color of a
JLabel, we need to call this method and pass the
void setOpaque(boolean value)
value true in parameter, in addition with the
setBackground( ) method.
This method is called to add an Action Listener
void addActionListener(ActionListener al)
to a component.
This method is called to add a Mouse Listener to
void addMouseListener(MouseListener ml)
a component.
As stated earlier, we need to write a class to develop a GUI and the object of that class will be the
GUI. Let the name of our class be FirstFrame. Let’s start our code:
import [Link].*;
Step import [Link].*;
0 import [Link].*;
import [Link].*;
Step public class FirstFrame extends JFrame implements ActionListener{
1 //ActionListener Interface is implemented because we will perform some actions on the two buttons
private JLabel nameLabel, passLabel;
private JTextField nameTF;
private JPasswordField passPF;
private JButton nextBtn, exitBtn;
Step
private JRadioButton r1, r2;
2
private ButtonGroup bg;
private JCheckBox c1, c2;
private JComboBox combo;
private JPanel panel;
Step private Color customColor;
3 private Font customFont;
Step public FirstFrame( )
4 {
super(“First Frame Demo”);
(a) [Link](800, 450);
[Link](JFrame.EXIT_ON_CLOSE);
panel = new JPanel( );
(b)
[Link](null);
customColor = new Color(180, 200, 150);
(c)
customFont = new Font(“Consolas”, [Link], 16);
(d) //Now, we will follow the three line pattern for each of the components
[1] nameLabel = new JLabel(“User Name: ”);
[2] [Link](50, 50, 100, 30);
[3] [Link](nameLabel);
[1] passLabel = new JLabel(“Password: ”);
[2] [Link](50, 100, 100, 30);
[3] [Link](passLabel);
[1] nameTF = new JTextField( );
[2] [Link](170, 50, 100, 30);
[3] [Link](nameTF);
[1] passPF = new JPasswordField( );
[2] [Link](170, 100, 100, 30);
[3] [Link](passPF);
[1] nextBtn = new JButton(“Next”);
[2] [Link](90, 170, 80, 30);
[3] [Link](nextBtn);
[1] exitBtn = new JButton(“Exit”);
[2] [Link](180, 170, 80, 30);
[3] [Link](exitBtn);
[1] r1 = new JRadioButton(“True”);
[2] [Link](250, 250, 80, 30);
[3] [Link](r1);
[1] r2 = new JRadioButton(“False”);
[2] [Link](350, 250, 80, 30);
[3] [Link](r2);
[1] c1 = new JCheckBox(“Burger”);
[2] [Link](250, 300, 80, 30);
[3] [Link](c1);
[1] c2 = new JCheckBox(“Pizza”);
[2] [Link](350, 300, 80, 30);
[3] [Link](c2);
//There is one additional line for JComboBox
[0] String items[ ] = new String [ ]{“C”, “C++”, “Java”, “Python”};
[1] combo = new JComboBox(items);
[2] [Link](250, 350, 100, 30);
[3] [Link](combo);
//As we want only one RadioButton to be selectable
[1] bg = new ButtonGroup( );
[2] [Link](r1);
[3] [Link](r2);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
(e)
[Link](customColor);
[Link](customFont);
[Link](customFont);
[Link](this);
[Link](this);
[Link](panel);
(f)
}
public void actionPerformed(ActionEvent ae)
{
String command = [Link]( );
if([Link]([Link]( )))
{
//to display a notification/message box
[Link](this, “This is a Message Box”);
}
else if([Link]([Link]( )))
Step
{
5
//to close the application
[Link](0);
}
else
{
//Write necessary codes
}
}
}
public class FrameDemo
{
public static void main(String args[ ])
Step {
6 First Frame ff = new FirstFarme( );
[Link](true);
}
}
Practice
Design a GUI with a TextField and a Button. Whenever you click on the button, the text
inside the TextField is displayed in a message box.