You are on page 1of 57

Chapter One

Java Graphical User Interface


(GUI)
Lecture by
Demeke G.

1
Outline
Overview of Java
Introduction to GUI
Overview of swing and AWT
GUI Event classes and Listener Interfaces
Swing and AWT Components and Containers
Layout Managers
Handling Events
Getting Input from user

2
Java Naming conventions
 Java naming convention is a rule to follow as you decide
what to name your identifiers such as class, package,
variable, constant, method etc.
 But, it is not forced to follow. So, it is known as
convention not rule.

3
Java Naming conventions
Name Convention
class should start with uppercase letter and be a noun e.g.
name
String, Color, Button, System, Thread etc.
interface should start with uppercase letter and be an
name
adjective e.g. Runnable, Remote, ActionListener etc.
method
name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.
variable should start with lowercase letter e.g. firstName,
name
orderNumber etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants
name should be in uppercase letter. e.g. RED,
YELLOW, MAX_PRIORITY etc.
4
Constructor
• Constructor is a special type of method that is used to
initialize the object.
• Constructor is invoked at the time of object creation.
• Constructor name must be same as its class name
• Constructor must have no explicit return type
• There are two types of constructors:
1) default constructor (no-arg constructor)
2) parameterized constructor

5
Package
•  A java package is a group of similar types of classes,
interfaces and sub-packages.
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) used to categorize the classes and interfaces so that they
can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

6
The import Keyword
• If class wants to use another class in the same package, the
package name does not need to be used.
• Classes in the same package find each other without any
special syntax.
• To refer a class in a different package
I. The fully qualified name of the class can be used. For
example: payroll.Employee
II. The package can be imported using the import
keyword and the wild card (*). For example:
import payroll.*;
Note: A class file can contain any number of import
statements. The import statements must appear after the
package statement and before the class declaration.
7
Assignment
Final methods, variables, classes
Static variables and methods
Instance Variables
Overloaded Constructors and Methods
Inheritance
Super and this Keywords
Java Access Modifiers
Interface

8
Graphical User Interface (GUI)
 A GUI presents a user-friendly mechanism for interacting
with an application.
 A GUI gives an application a distinctive “look” and “feel.”
 Consistent user interfaces enable a user to learn new
applications faster.
 There are actually two sets of GUI components in Java
which are AWT and Swing.
 Before Swing was introduced in Java SE 1.2, Java GUIs
were built with components from the Abstract Window
Toolkit(AWT)
 The component’s appearance and the way in which the user
interacts with it are known as its look-and-feel.
9
Abstract window toolkit(AWT)
 The AWT contains numerous classes and methods that
allow you to create and manage windows
 AWT components are heavyweight, because they rely on
the local platform’s windowing system to determine their
functionality and their look-and-feel.
 The AWT classes are contained in the java.awt package.
Some AWT Classes are :

10
Class Description
Frame Creates a standard window that has a title bar, resize
corners, and a menu bar.
Panel The simplest concrete subclass of Container
Image Encapsulates graphical images.
Menu Creates a pull-down menu.
MenuBar Creates a menu bar.
MenuItem Creates a menu item.
Label Creates a label that displays a string.
List Creates a list from which the user can choose. Similar to
the standard Windows list box.
TextArea Creates a multiline edit control.
TextField Creates a single-line edit control
Button Creates a push button control.
Checkbox Creates a check box control.
11
Class Description
BorderLayout The border layout manager. Border layouts use five
components: North, South, East, West, and Center.
GridLayout The grid layout manager. Grid layout displays
components in a two- dimensional grid.
FlowLayout The flow layout manager. Flow layout positions
components left to right, top to bottom.
Color Manages colors in a portable, platform-independent
fashion.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other
components
Event Encapsulates events.
12
Overview of Swing Components
 Swing is the next-generation GUI toolkit that Sun
Microsystems is developing to enable enterprise
development in Java.
 Programmers can use Swing to create large-scale Java
applications with a wide array of powerful components.
 Swing GUI components from package javax.swing that are
used to build Java GUIs.
 Most Swing components are lightweight b/c they are purely
java and platform independent.

13
Swing Features
1. Pluggable Look-and-Feels
• SWING based GUI Application look and feel can be
changed at run time based on available values.
2. Lightweight Components
• Components are not dependent on native peers to render
themselves. Instead, they use simplified graphics primitives
to paint themselves on the screen and can even allow
portions to be transparent.
3. Additional Features: Several other features distinguish
Swing from the older AWT components. Such as new
components, tooltip and bind keyboard event.

14
Cont..
A wide variety of new components, such as tables,
trees, sliders, progress bars, internal frames, and text
components.
Swing components can have tooltips placed over them. A
tooltip is a textual popup that momentarily appears when
the mouse cursor rests inside the component's painting
region.
You can arbitrarily bind keyboard events to
components, defining how they will react to various
keystrokes under given conditions.

15
The Swing component hierarchy

16
Swing Components
Component Description
JLabel Displays uneditable text or icons
JTextFieldEnables user to enter data from the keyboard. Can also
be used to display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user
can make a selection by clicking an item or possibly by
typing into the box.
JList Provides a list of items from which the user can make a
selection by clicking on any item in the list. Multiple
elements can be selected
JPanel Provides an area in which components can be placed and
organized. Can also be used as a drawing area for
graphics.
17
Cont..
Component Description
JTable The JTable is used to display and edit regular two-
dimensional tables of cells.
JTabbedPane A component that lets the user switch between a group
of components by clicking on a tab with a given title
and/or icon.

JScrollPane Provides a scrollable view of a lightweight component


JMenu An implementation of a menu -- a popup window
containing JMenuItems that is displayed when the
user selects an item on the JMenuBar.

JMenuBar An implementation of a menu bar.

18
Cont..
Component description

JMenuItem An implementation of an item in a menu.


JOptionPane makes it easy to pop up a standard dialog
box that prompts users for a value
JSplitPane used to divide two Components
JColorChooser provides a pane of controls designed to
allow a user to select a color
JFileChooser A UI for choosing files and directories
JSpinner A single line input field that lets the user
select a number or an object value from an
ordered sequence.
19
Introduction to Layout Managers
 Layout means the arrangement of components within the
container.
 Layout managers arrange GUI components in a container
for presentation purposes.
 All layout managers implement the interface
LayoutManager (in package java.awt).
 The layout manager automatically positions all the
components within the container. If we do not use layout
manager then also the components are positioned by the
default layout manager.
 Some of the layout manager classes are FlowLayout,
BorderLayout, GridLayout , GridBagLayout etc..
20
1. FlowLayout
 Places components sequentially (left to right) in the order
they were added.
 Default for javax.swing.JPanel.
 It’s also possible to specify the order of the components by
using the Container method add, which takes a Component
and an integer index position as arguments.
 The components are center aligned by default
 Allows GUI components to be left aligned,
Centered (the default) and right aligned.
i.e. add(component, FlowLayout.LEFT);

21
2. BorderLayout
Default for JFrames (and other windows). Arranges the components
into five areas: NORTH, SOUTH, EAST, WEST and CENTER.
ABorderLayout limits a Container to containing at most five
components . i.e
button1 =new Jbutton(“top”); button2 =new Jbutton(“Bottom”);
button3 =new Jbutton(“Right”); button4 =new Jbutton(“Left”);
button5=new Jbutton(“center”);
private BorderLayout layout;// borderlayout object
layout = new BorderLayout(5,5); // 5 pixel gaps
setLayout( layout ); // set frame layout
add( buttons1,BorderLayout.NORTH);// add button to north
add( buttons2,BorderLayout.SOUTH);// add button to south
add( buttons3,BorderLayout.EAST); // add button to east
add( buttons4,BorderLayout.WEST);// add button to west
add( buttons5,BorderLayout.CENTER );// add button to center 22
3. GridLayout
 Arranges the components into rows and columns
 Every Component in a GridLayout has the same width and
height
 Components are added to a GridLayout starting at the top-
left cell of the grid and proceeding left to right until the row
is full.
i.e private GridLayout gridLayout1; 2 rows 3 columns
5 Hgap and 5 Vgap
private GridLayout gridLayout2;
gridLayout1 = new GridLayout( 2, 3,5,5);
gridLayout2 = new GridLayout( 3, 2)
setLayout( gridLayout1 ); 3 by 2
No gaps
23
4. GridBagLayout
 This is the most flexible and complex layout manager class.
 The object of GridBagLayout aligns the component
vertically, horizontally or along their baseline without
requiring the components of same size.
 A GridBagConstraints object describes how a component
is placed in a GridBagLayout
i.e. GridBagLayout gridbag= new GridBagLayout();

24
GridBagConstraints fields and Description
•anchor: Specifies the relative position (NORTH,
NORTHEAST, EAST, SOUTHEAST, SOUTH,
SOUTHWEST, WEST, NORTHWEST, CENTER)of the
Component in an area that it does not fill.
•fill : Resizes the component in the specified direction
(NONE,HORIZONTAL, VERTICAL, BOTH) when the
display area is larger than the component.
•gridx: The column in which the component will be placed.
•gridy :The row in which the component will be placed.
•gridwidth: The number of columns the component
occupies.
•gridheight: The number of rows the component occupies.
•weightx: The amount of extra space to allocate horizontally.
25
Cont.…
• The grid slot can become wider when extra
space is available.
• weighty: The amount of extra space to allocate
vertically. The grid slot can become taller when
extra space is available.
Example

26
Example
• the JComboBox (displaying “Iron”) has a gridx value of 1
and a gridy value of 2.
• The JComboBox occupies two columns and one rows.
• The JTextArea on the left side occupies three rows.
• Variable weightx specifies how to distribute extra
horizontal space to grid slots in a GridBagLayout when the
container is resized. A zero value indicates that the grid slot
does not grow horizontally on its own. However, if the
component spans a column containing a component with
nonzero weightx value, the component with zero weightx
value will grow horizontally in the same proportion as the
other component(s) in that column. This is because each
component must be maintained in the same row and column
in which it was originally placed. 27
Example cont..
• Variable weighty specifies how to distribute extra
vertical space to grid slots in a GridBagLayout when
the container is resized. A zero value indicates that the
grid slot does not grow vertically on its own. However,
if the component spans a row containing a component
with nonzero weighty value, the component with zero
weighty value grows vertically in the same proportion
as the other component(s) in the same row.
• The effects of weighty and weightx cannot easily be
seen until the container is resized and additional space
becomes available . Components should be given
nonzero positive weight values otherwise
they’ll“huddle” together in the middle of the container.28
Delegation Model
• Events in Java are fired and handled using a design
known as the delegation model.
• With the delegation model, a source generates an
event and a listener handles it.
• There are three major players in the delegation
model:
1. The source of the event: In GUI, the component
is the source of the event. Events are Java objects
that are instantiated by the component and passed
as an argument to any listeners

29
Cont..

2.An event listener


• A listener of an event registers itself with the source
of the event. When an event occurs, the source of
the event invokes a method on the listener.
3. An interface
• The interface contains the methods that the listener
must implement and that the source of the event
invokes when the event occurs.

30
Example
 when a user clicks a Button, the Button generates a
ActionEvent. The Button invokes the actionPerformed()
method on each registered listener of the Button, passing in
the ActionEvent object. The actionPerformed() method is
defined in the ActionListener interface, which each listener
must implement.
 In this scenario, the Button is the source of the event, the
interface is ActionListener, and the listener is any class
that implements ActionListener and registers itself with the
Button.

31
Handling Events
 An event is an object that’s generated when the user does
something
For example, if the user clicks a button, drags the mouse over
a label, or selects an item from a combo box, an event object is
generated. This event object is then passed to a special method
you create called an event listener. The event listener can
examine the event object, determine exactly what type of
event occurred, and respond accordingly.
 Event handling is provided by AWT, not by Swing
 There are several different types of event objects,
represented by various classes that all inherit AWTEvent.

32
Event Class Listener Interface Description
ActionEvent ActionListener Created when the user has clicked the button,
tabbing to the button and pressing the Enter key
ItemEvent ItemListener Created when the selected item in a list control,
such as a combo box or list box, is changed.
DocumentEvent DocumentListener Created when the user changes the contents of a
text component. such as a text field
WindowEvent WindowListener Created when the status of the window (frame)
changes.
KeyEvent KeyListener Created when the user presses a key on the
keyboard.
MouseEvent MouseListener Created when the user clicks one of the buttons,
drags the mouse, or simply moves the mouse
over another object.

FocusEvent FocusListener Created when a component receives or loses


focus.
33
Common GUI Events

34
Event Listener Interfaces
 The event listener interface contains the methods that the
event source invokes on the listener, and it provides the
means of communication between the source of the event
and the listener of the event.
 Java uses a standard naming convention for event classes
and listener interfaces:
 The name of the event class uses the convention <Name>Event,
and
 the corresponding listener interface uses the
convention <Name>Listener.

35
Example
 ActionEvent class is associated with the one
method of the ActionListener interface,
 WindowEvent class is associated with the seven
methods of the WindowListener interface.
MouseEvents by MouseListeners and
MouseMotionListeners, and
 KeyEvents by KeyListeners.

36
37
Methods Defined by Event Listener Interfaces
Listener Interface Method Description
ActionListener void actionPerformed Called when an action
(ActionEvent e) event
ItemListener void itemStateChanged Called when the selected
(ItemEvent e) item changes
DocumentListener void changeUpdate Called when text is
(DocumentEvent e) changed.
void insertUpdate Called when text is
(DocumentEvent e) inserted.
void removeUpdate Called when text is
(DocumentEvent e) deleted.
FocusListener void focusGained Called when the
(FocusEvent e) component gains focus
void focusLost Called when the
(FocusEvent e) component looses focus
38
Cont..
Listener Method Description
Interface
KeyListener void keyPressed Called when the user presses a key.
(KeyEvent e)
void keyReleased Called when the user releases a key.
(KeyEvent e)
void keyTyped Called when the user types a key
(KeyEvent e)
MouseListener void mouseClicked Called when the user clicks the mouse.
(MouseEvent e)
void mouseEntered Called when the mouse moves over a
MouseEvent e) component
void mouseExited Called when the mouse leaves a
(MouseEvent e) component.
void mousePressed Called when the user presses the mouse
(MouseEvent e). button
void mouseReleased Called when the user releases the
(MouseEvent e) mouse button

39
Cont..
Listener Method Description
Interface
WindowListener void windowActivated Called when the window is
(WindowEvent e) activated
void windowClosed Called when the window has
(WindowEvent e) been closed.
void windowClosing Called when the user attempts
(WindowEvent e) to close the window.
void windowDeactivated Called when the window is
(WindowEvent e). deactivated
void windowDeiconified Called when the window is
(WindowEvent e) changed from icon to normal
void windowIconified Called when the window is
(WindowEvent e) minimized to an icon

40
Cont..

To write Java code that responds to events, you have


to do the following:
1. Create a component that can generate events
• You want to add buttons or other components that
generate events to your frame. All Swing
components can generate some events.
• You declare the variable that refers to the event
source as a private class field, outside of the
constructor for the frame or any other method.
• For example private JButton button1;
41
Cont..
Then, in the constructor for the frame class, you can
create the button.
JPanel panel = new JPanel();
button1 = new JButton(“Click me!”);
panel.add(button1);
this.add(panel);
Note that this code appears in the constructor of
the frame class, so this in the last line refers to the
frame.

42
2. Create a class that implements the listener interface
To handle action events, you should create a class that
implements the ActionListener interface
One of the easiest way is to simply add implements
ActionListener to the definition of the frame class. Thus,
the frame class declaration looks something like this:
public class ClickMe extends JFrame implements
ActionListener
3.Write the code for any methods defined by the listener
• When you implement a listener interface, you must
provide an implementation of each method defined by
the interface.
• For example the ActionListener interface defines a
method named actionPerformed. 43
Cont..
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button1)
button1.setText(“You clicked!”);
}
Here, this code changes the text displayed by button1 if the
event source is button1.
4. Register the listener with the source
 Every component that serves as an event source provides a
method that lets you register event listeners to listen for the
event.

44
Cont..
For ActionEvent sources, the method is
addActionListener.
Here’s a modification to the frame constructor code
that creates the button1 button and registers the frame
class as the action event listener
JPanel panel = new JPanel();
button1 = new JButton(“Click me!”);
button1.addActionListener(this); (add<Event_Name>Listener())
panel.add(button1);
this.add(panel);
 Here, you can specify this as the event listener because
the frame class itself implements ActionListener. 45
Cont..
import javax.swing.*; button1 = new JButton(“Click Me!”);
import java.awt.event.*; 1 button1.addActionListener(this);
public class ClickMe panel1.add(button1);
extends JFrame implements this.add(panel1);
ActionListener this.setVisible(true);
4
{ }
public static void main(String [] args) private int clickCount = 0;
{ public void actionPerformed(ActionEvent e)
new ClickMe(); 2 {
} if (e.getSource() == button1) 5
private JButton button1; 3 {
public ClickMe() clickCount++;
{ if (clickCount == 1)
this.setSize(200,100); button1.setText(“I’ve been clicked!”);
this.setDefaultCloseOperation(JFrame.EXI else
T_ON_CLOSE); button1.setText(“I’ve been clicked “+ clickCount
this.setTitle(“I’m Listening”); + “ times!”);
JPanel panel1 = new JPanel(); }
}
46
}
Using Inner Classes to Listen for Events
An inner class is a class that’s nested within another class.
Inner classes are commonly used for event listeners.
public ClickMe2()
private class ClickListener
{
implements ActionListener ➞22
this.setSize(200,100);
{
this.setDefaultCloseOperation(
private int clickCount = 0;
JFrame.EXIT_ON_CLOSE); 19
public void actionPerformed(ActionEvent e)
this.setTitle(“I’m Listening”);
{
ClickListener cl = new ClickListener();
if (e.getSource() == button1) ➞23
➞20
{
JPanel panel1 = new JPanel();
clickCount++;
button1 = new JButton(“Click Me!”);
if (clickCount == 1)
button1.addActionListener(cl); ➞21
button1.setText(“I’ve been clicked!”);
panel1.add(button1);
else
this.add(panel1);
button1.setText(“I’ve been clicked “
this.setVisible(true);
+ clickCount + “ times!”);
}
}}} 47
Cont..
19 The setDefaultCloseOperation method tells the Jframe
class that no default action is taken if the user closes the
window.
➞20 This statement creates an instance of the ClickListener
class (the inner class) and assigns it to the variable c1.
➞21 This statement adds c1 as an action listener for the button
➞22 The ClickListener class is declared as an inner class by
placing its declaration completely within the ClickMe2 class.
The ClickListener class implements the ActionListener
interface so it can handle action events.
➞23 The button1 variable is available to the inner class here
because inner classes can access private members of the class
that contains them.
48
Getting Input from the User
1. A text field: is a box that the user can type text in. You create text
fields by using the JTextField class
Constructor Description
JTextField() Creates a new text field
JTextField(int cols) Creates a new text field with the specified width
JTextField(String text, int cols) Creates a new text field with the specified width and
initial text value
Method Description
String getText() Gets the text value entered into the field.
void setColumns(int cols) Sets the size of the text field. (Better to do this in the
constructor.)
void setEditable (boolean value) If false, makes the field read-only.
void setText(String text) Sets the field’s text value.
void setToolTipText (String text) Sets the tooltip text that’s displayed if the user rests
the mouse over the text field for a few moments
49
2. TextArea
•Constructed from JTextArea class . This class have the following methods
void append(String text) Adds the specified text to the end of the text
area’s text value.
•int getLineCount() Gets the number of lines currently in the text value.
•String getText() Gets the text value entered into the field.
•void insert(String str, int pos) Inserts the specified text at the specified
position.
•void replaceRange(String str, int start, int end) Replaces text indicated
by the start and end position with the new specified text.
•void setEditable(boolean value) If false, makes the field read only.
•void setLineWrap(boolean value) If true, lines wrap if the text doesn’t fit
on one line.
•void setText(String text) Sets the field’s text value.
•void setToolTipText (String text) Sets the tooltip text.
50
3. Checkbox
• To create a check box, you use the JCheckBox class
• Some Jcheckbox class Methods are
• void addActionListener (ActionListener listener) Adds an
ActionListener to listen for action events.
• void addItemListener(ItemListener listener) Adds an
ItemListener to listen for item events.
• String getText() Gets the text displayed by the check box.
• Boolean isSelected() Returns true if the check box is checked,
false if the check box is not checked.
• void setSelected(boolean value) Checks the check box if the
parameter is true unchecks it if the parameter is false.
• void setText(String text) Sets the check box text.
• void setToolTipText (String text) Sets the tooltip text that’s
displayed if the user rests the mouse over the check box for a few
moments. 51
3. Radio Buttons
• To work with radio buttons, you use two classes. First, you create the
radio buttons themselves with the JRadioButton class, Then, you
create a group for the buttons with the ButtonGroup class
• void addActionListener (ActionListener listener) Adds an
ActionListener to listen for action events.
• void addItemListener(ItemListener listener) Adds an ItemListener
to listen for item events.
• String getText() Gets the text displayed by the radio button.
• Boolean isSelected() Returns true if the radio button is selected, false
if the radio button is not selected.
• void setSelected(boolean value) Selects the radio button if the
parameter is true.
• void setText(String text) Sets the radio button text.
• void setToolTipText (String text) Sets the tooltip text

52
4.Combo Boxes
• Use the JComboBox class to create combo boxes
• methods of this class are :
• void addActionListener(ActionListener listener)
Adds an action listener to the combo box.
• void addItem(Object item) Adds the item to the combo box.
• void addItemListener(ItemListener listener) Adds an item
listener to the combo box.
• Object getItemAt(int index) Returns the item at the specified
index
• int getItemCount() Returns the number of items in the combo box
• int getSelectedIndex() Returns the index of the selected item.
• Object getSelectedItem() Returns the selected item.
• void insertItemAt(Object item, int index) Inserts an item at a
specified index. 53
Cont..
• Boolean isEditable() Indicates whether or not the combo box’s text
field is editable.
• void removeAllItems() Removes all items from the combo box.
• void removeItem(Object item) Removes the specified item.
• void removeItemAt(int index) Removes the item at the specified
index.
• void setEditable(boolean value) Specifies whether or not the
combo box’s textfield is editable.
• void setMaximumRowCount (int count) Sets the number of rows
displayed when the combo box list is dropped down.
• void setSelectedIndex(int index) Selects the item at specified
index. Throws IllegalArgumentException if the index is less than
zero or greater than the number of items in the combo box.
• void setSelectedItem (Object item) Selects the specified item.
Throws IllegalArgumentException if the 54
5.List
• You use the JList class to create list boxes
• int getSelectedIndex() Returns the index of the first selected item, or
–1 if no items are selected.
• int[] getSelectedIndexes() Returns an array with the index of each
selected item. The array is empty if no items are selected.
• Object getSelectedValue() Returns the first selected item, or null if
no items are selected.
• Object[] getSelectedValues() Returns an array with all the selected
items. The array is empty if no items are selected.
• boolean isSelectedIndex (int index) Returns true if the item at the
specified index is selected.
• boolean isSelectionEmpty() Returns true if no items are selected.

55
• void setFixedCellHeight(int height)
Sets the height of each row.
• void setFixedCellWidth(int width)
Sets the width of each row.
• void setSelectedIndex(int index)
Selects the item at the specified index.
• void setSelectionMode (int mode)
Sets the selection mode. Allowable values are:
ListSelectionModel.SINGLE_SELECTION,
ListSelectionModel.SINGLE_INTERVAL_SELECTION, and
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION.
• void setVisibleRowCount(int value)
Sets the number of rows displayed by the list.

56
End of chapter
Thank you !!!

57

You might also like