1
Java GUIs
Dr. Randy M. Kaplan
2
Constructing User Interfaces
From a functionality standpoint there are two things that every program must implement Interaction Computation
3
Constructing User Interfaces
As Java evolved as a browser based language, it provides a rich set of tools for interacting with a program user
Originally these tools were embodied in the java.awt or Abstract Windowing Toolkit
AWT is platform dependent Look and feel is determined by the platform
Java 2 incorporated the Swing components Look and feel is independent of the platform
4
Constructing User Interfaces
Swing Component Advantages “Lightweight” Written entirely in Java Not weighed down by platform specific issues
5
Model-View-Controller Architecture Swing
Loosely based on the Model-View-Controller architecture (MVC)
Model Stores data which defines the component
View Creates the visual representation of the component from the
data in the model Controller
Deals with the interaction with the component and modifies the model and/or the view in response to a user action as necesary
6
Basics – 1
A CONTAINER is a collection of related components
The content pane is a container that will be used to contain the interface components
Components are added to a container with the add method
7
Creating a Window
A basic window in Java is represented by an object of the class Window in the package java.awt
Objects of the class are hardly ever used directly because Borders and title bars are pretty much always part
of a window and the Class Window does not provide these
JFrame in javax.swing includes these features and others
8
JFrame HierarchyObject
Component
Container
Window
Frame
JFrame
Defines a component, which isan object that can be display
such as a button or a scrollbar
Defines a component thatcontains other components
Defines a basic window withno title bar or border
Defines a window with a titlebar and a border
A frame with extendedcapabilities
Java.lang
Java.swing
{Java.awt
9
Displaying an Application Window
10
Components and Containers
Component Represents a graphical entity that can be
displayed on the screen Any object of a class that is a subclass of a
Component
11
Key Classes in the Window Hierarchy JFrame
Basic Java Application Window Has
Title bar Provision for adding menu
Subclass this class to create a window class specific to your application
12
Key Classes in the Window Hierarchy JDialog
Define a dialog window Enter data into a program in barious ways
JApplet Basic class for a Java 2 applet All Java 2 applets will have this class as a base
class Drawing is possible in a JApplet Add menus and other components
13
Key Classes in the Window Hierarchy JComponent
Subclasses of JComponent define a range of standard components
14
Window Panes
Add components or draw in a window displayed from a JFrame object – You add the components or draw on a window
pane that is managed by the JFrame object Window panes are objects that are
containers which represent an area of a window
Window panes come in several different types
15
Window PanesEnter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
16
Window Panes
The area below the title bar in a JFrame corresponds to a JRootPane object
The JRootPane object contains another pane – the layeredPane
Enter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
17
Window Panes
The area below the title bar in a JFrame corresponds to a JRootPane object
The layeredpane area corresponds to the area occupied by JRootPane
If there is a menu bar it is managed by the layeredPane
Enter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
18
Window Panes
The area below the menu bar corresponds to the contentPane object
The contentPane object is where components are typically placed
Enter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
19
Window Panes
The layeredPane object has special properties
Advanced applications may permit groups of components to be managed in separate layers that overlay one another within the pane
Layers are displayed in order from back to front
Enter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
20
Window Panes
One additional pane, the glassPane object, corresponds to the JRootPane area
The glassPane displays on top of all the other panes
The glassPane is used to display components that will always remain on top
Enter Title Here
Jframe Window
Optional menu bar
The area of the window below the titlebarcorresponds to a JRootPane object
layeredPane object of type JLayeredPane
contentPane object of type JInternalPane
The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member
of the Jframe object
21
JFrame Class Methods to access panesMethod Description
getRooPane() Returns the root pane as type JRootPane
getLayeredPane() Returns the root pane as type JLayeredPane
getContentPane() Returns the content pane as type Container. This is the method that you will use most frequently, since components will normally be added to this pane
getGlassPane() Returns the glass pane as type component
22
Component Attributes
The component class defines attributes that record the following information about a component object Position Name Size Foreground color Background color Cursor Enabled Visible
23
Methods for Size and Position setBounds(int x, int y, int width, int height) setBounds(Rectangle rect) Rectangle getBounds setSize(Dimension d) Dimension getSize() setLocation(int x, int y) setLocation(Point p) Point getLocation()
24
Basics – 2
JComponent is the superclass to most Swing components
This class defines the common attributes and behaviors of all subclasses of JComponent
25
Basics – 3
JLabel Subclass of JComponent Displays a
single line of read-only text
Image Text and image
26
Basics – 4
Basic Interface Construction
27
Using Containers
A container is any class with the Container class as its base class
All Swing components are containers The Container class is the direct base class
for the Window class which gives the Window class the ability to contain other object
Container is called an abstract class which means that instances of the Container class cannot be created
28
Using Containers
Components within a container are displayed within the area of the container
A container controls how its embedded components are laid out by means of a layout manager
29
Container Class
Basic Methods int getComponent()
Returns a count of the number of components contained by the current component
Component getComponent(int index) Returns the component identified by the index value
Component [] getComponents() Returns an array of components in the current container
30
Container Class
Adding Components Components are recorded in an array within the
Container object The array is increased in size to accommodate as
many components as are present To add a component to a contained use the
method add()
31
Add Methods
Component add(Component c) Add the component c to the end of the list of components
stored in the container Component add(Component c, int index)
Add the component c to the list of components in the container at the position specified by index
If index == -1 then the component is added to the end of the container
void add (Component c, Object constraints) void add (Component c, Object constraints, int
index)
32
Basics – 4
Basic Interface Construction
A class is going to be defined that will extend the functionality of a graphics element container like a JFrame
33
Basics – 5
Basic Interface Construction
The content pane contains what will be displayed. We need to retrieve it so we can use it to display our graphical components
34
Basics – 6
Basic Interface Construction
Graphics elements like JLabel are created and added to the content pane
35
Basics – 7
Basic Interface Construction
The size of the frame is set and the state of the frame is set to visible
36
Basics – 8
Basic Interface Construction
A new instance of the class is created and the creation of it causes the instance of the JLabel to be displayed
37
Events – 1
The previous class definition showed the basic elements of how a user interface element is added to a class method
Labels are static non-interactive interface elements
Besides being able to display elements we would also like to be able to capture interface element interactions
38
Event-Driven Progams
Operating System
Keystrokes Keystrokes Mouse Actions
Java Library Classes
Program method method method method
Events
39
Events – 2
Event Handling Three Parts
Event source Event object Event listener
40
Events – 3
Event Handling Three Parts
Event source The particular interface component with which the user
interacts Event object Event listener
41
Events – 4
Event Handling Three Parts
Event source Event object
Encapsulates information about the event that occurred Reference to the event source Specific event information that is required by the event
listener Event listener
42
Events – 5
Event Handling Three Parts
Event source Event object Event listener
Receives an event object when it is notified of the event Uses the event object to respond to the event
43
Events – 6
Two Key Programmer Responsibilities Register a listener for the event Implement an event handler for the event
44
Events
What happens when an event occurs? A user clicks a button in the GUI for your program The button is the source of this event The event generated as a result of the mouse
click is associated with the JButton object in your program that represents the button on the screen
45
Events
When the button is clicked – A new object is created The object represents and identifies this event For a button, the object is an instance of the class
ActionEvent The object will contain information about the event and its
source Any event that is passed to a Java program will be
represented by a particular event object The object will be passed as an argument to the
method that is to handle the event
46
Events
Button
Click
OK
Creates
ActionEventobject
The listener connects to theevent source by calling
addActionListener() methodfor the source object
Passed to
public class MyButtonHandler implementsActionListener{
// class members// Constructor…button.addActionListener(this);…void actionPerformed(ActionEvent e){
// Handle the event}
}
47
Events
The event object corresponding to the button click will be passed to any listener object that has previously registered an interest in this kind of event
A listener object is simply an object that listens for particular events
A listener object is also called a target for an event
48
Defining a Listener
Objects of any class can be made listeners by implementing a listener interface
There are many kinds of listener interfaces that cater to the different kinds of events
Each kind of listener interface defines particular methods for receiving the events that that listener has been designed to deal with
In addition to implementing the listener, the listener has to be connected to its source
49
Kinds of Events
Low-level Events Events arising from the keyboard or from the
mouse Events associated with operation on a window –
such as reducing it to an icon or closing it Semantic Events
Specific component related events Pressing a button by clicking it to cause some program
action Adjusting a scrollbar
50
Low-level Events
FocusEvent Objects of this class represent events that originate when a
component gains or loses focus MouseEvent
Objects of this class represent events that result from user action with the mouse such as moving the mouse or pressing a mouse button
KeyEvent Objects of this class represent events that arise from pressing
keys on the keyboard WindowEvent
Objects of this class represent events that relate to a window such as activating or deactiviating a window, reducing a window to its icon or closing a window
51
JTextField and JPasswordField – 1
52
JTextField and JPasswordField – 2 Single-line areas Text is entered by a user Text can be displayed A JPasswordField shows that a character
was typed but hides the characters When the user presses the ENTER key in a
JTextField or JPasswordField an event occurs
53
JTextField and JPasswordField – 3
Declare the text fields and add the fields to the container.
54
JTextField and JPasswordField – 4
Each of the field gets an event handler
55
JTextField and JPasswordField – 5
The main gets specified as before. Declare a new instance which causes the code of the instance to run
56
JTextField and JPasswordField - 6
57
JTextField and JPasswordField – 7
The listener that is used is a new class that extends the functionality of the ActionListener – the main class for implementing event Listeners
58
JTextField and JPasswordField – 8
actionPerformed is an abstract method that is defined for ActionListener. This abstract method is invoked when an event occurs. It must be defined for the listener in order to respond to the event that occurs
59
JTextField and JPasswordField – 8
When actionPerformed is invoked, it is pass event, an object that contains information about the event that just occurred. It is this object that is examined in the code that follows to determine what actually occurred in the event
60
JTextField and JPasswordField – 9
The getSource method returns a reference to the interface object involved in the event. We can use this reference to make decisions about how to respond to the event
61
JTextField and JPasswordField – 10
We can retrieve the specific command that occurred in an event with the getActionCommand() method
62
Event Listeners
Each type of event has its associated listener Action events are handled by ActionListeners MouseEvents are handled by MouseListeners Key events are handled by KeyListeners
63
Event Handling – 1
Let’s consider event handling in more detail There are two things that are important to
keep in mind when writing code to handle events
These are: Getting an event handler registered Connecting the GUI component to the code that
will execute when an action involving it is executed
64
Event Handling – 2
An event has a listener registered for it using code like the following – textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler );
Every JComponent has an object of class EventListenerList called listenerList as an instance variable
All registered listeners are stored in the listenerList
65
Event Handling – 3
When the statement, textField1.addActionListener( handler );
is executed, a new entry is placed in the listenerList for textField1
Both a reference to the listener object and type of listener are recorded
66
Event Handling – 4
Types of Listeners How does a GUI component know to call the correct event
handling method? Every component supports several event types
Mouse events Key events Action events
When an event occurs, the event is dispatched only to those listeners of the appropriate type
The dispatch simply is calling the event handling method for each registered listener for that event type
67
Event Handling – 5
Each event Has a corresponding event-listener interface ActionEvents
Are handled by ActionListeners MouseEvents
Are handled by MouseListeners KeyEvents
Are handled by KeyListeners
68
Event Handling – 6
When an event occurs – A user generates an interaction with a component The component is handed a unique event ID
The event ID specifies the event type that occurred The GUI component uses the event ID to decide the type of
listener In the case of an ActionEvent, the event is dispatched to
every registered ActionListener’s actionPerformed method In the case of a MouseEvent, the event is dispatched to every
registered MouseListener The event ID of the MouseEvent determines which of the seven
different mouse event handling methods are called
69
JButton
A button is a component that a user clicks to trigger a specific action
There are several different types of buttons – Command buttons Check boxes Toggle buttons Radio buttons
70
JButton
When the ButtonTest program is run, a panel with two buttons is displayed
71
JButton
plainButton = new JButton( "Plain Button" ); container.add( plainButton );
Icon bug1 = new ImageIcon( "c:\\javaprj\\bug1.gif" ); Icon bug2 = new ImageIcon( "c:\\javaprj\\bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); container.add( fancyButton );
72
JButton ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler );
Code that registers the event handlers for each of the buttons
private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( null, "You pressed: " + event.getActionCommand() ); } }
The event handler shows a message dialog that displays the name of the button that was clicked
73
JCheckBox and JRadioButton
Swing has three types of state buttons JToggleButton
Frequently used in toolbars JCheckBox
Individual boxes that can be checked JRadioButton
Groups of buttons in which only one can be set
74
JCheckBox
A check box allows the state of this UI component to be set or unset
The check box UI components are independent of one another
75
JCheckBox
The event handler for these checkboxes contains the code to change the font characteristics of the text box
private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;
// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }
76
JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;
// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }
The type of listener required for the checkBox GUI component is an ITEMLISTENER
77
JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;
// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }
When the state of a check box is changed, the method itemStateChanged is invoked
78
JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;
// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }
We check the current state of each of the check boxes and set the font characteristics accordingly
79
JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;
// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }
Lastly, the font of the field is set to change the visible characteristics of the font
80
Layouts
You have seen the following code used container.setLayout( new FlowLayout() );
This code specifies the type of layout that will be used to place the components in the display container
What exactly is a flow layout?
81
Layouts
Layouts managers are provided to arrange components on a container for presentation purposes
The idea is that by providing these managers it is easier than specifying the exact positions of the components
Programmers concentrate on basic look and feel and the layout manager takes care of the rest
82
Layouts
Types of Layouts FlowLayout
Components are placed sequentially left to right in the order they were added
Default layout manager for Applet Panel JPanel
BorderLayout GridLayout
83
Layouts
Types of Layouts FlowLayout BorderLayout
Arranges the components into five areas – North, South, East, West, and Center
Default for JFrame GridLayout
84
Layouts
Types of Layouts FlowLayout BorderLayout GridLayout
Arranges the components into rows and columns
85
FlowLayout
Most basic layout manager Components are placed left to right in the
order they are added to the container When the edge of the container is reached,
components are continued on the next line Components can be
Left aligned Centered (default) Right aligned
86
FlowLayout
The next example creates three buttons in a FlowLayout
Buttons are labeled Left Center Right
Clicking left Sets the flow layout alignment to left
Clicking right Sets the flow layout alignment to right
Clicking center Sets the flow layout alignment to center
87
FlowLayout
Left Aligned
Centered
Right Aligned
88
FlowLayout
The “container” is a JFrame
89
FlowLayout
Create the layout object
90
FlowLayout
Get the container’s content pane
91
FlowLayout
Set the layout to be a flowlayout (set the container’s layout)
92
FlowLayout
Setting up a button
Create the new button
93
FlowLayout
Setting up a button
“On the fly”, create an instance of a listener class.
This is called an “inner class” because it is defined with another class
It is “anonymous” because it is defined ONLY for this button
94
FlowLayout
Setting up a button
The action to be performed is to set the layout’s alignment – in this case to left aligned
95
FlowLayout
Setting up a button
The layout if forced to realign (visibly) due to this statement
96
FlowLayout
Setting up a button
Once the action has been defined for the button, it is added to the container
97
BorderLayout
BorderLayout Is the default layout for the contain pane Arranges components into five regions
NORTH SOUTH EAST WEST CENTER
Up to 5 components can be added to a BorderLayout The component placed in a region can actually be another
container to contain other components
98
BorderLayout
Schematic View of Regions
North
South
East WestCenter
As tall as component placed in the region
As wide as the component placed in the region
99
BorderLayout
Schematic View of Regions
North
South
Center
If the EAST and WEST regions are not occupied, the center region expands to fill the regions
100
BorderLayout
Schematic View of Regions
East WestCenter
If the NORTH and SOUTH regions are not occupied, EAST and WEST expand vertically
101
BorderLayout
Example
Horizonal gap between components
Vertical gap between components
Default gap is 0 (ZERO) pixels
102
GridLayout
Divides the container into a grid Components are laid out in rows and
columns Every component in a grid layout has the
same width and height Components are added to a grid
Left to right Top to bottom Until the grid is full
103
GridLayout
Example
104
GridLayout
Create two layouts
105
GridLayout
The first layout has 2 rows and 3 columns, and
the inter row/column spacing is 5
pixels
106
GridLayout
The second layout contains
3 rows and 2 columns and
the inter row/column spacing is 0
pixels
107
GridLayout
The buttons are added to the
container here
108
GridLayout
The total dimensions of the container
are defined here
The buttons of the layout are
sized according to the total dimension
109
GridLayout
Changing the dimension to 500 x 500
110
Panels
When a complex GUI is designed It is desirable to place components in an exact
location Complex GUI’s often consist of multiple PANELS Components within a panel are arranged in a
specific layout
111
Example
Get the containing content frame
112
Example
Create and array to hold 5 buttons
113
Example
Create the panel that will contain the buttons
114
Example
Set the layout of the panel containing the buttons to be a 1 row x # of buttons grid layout
115
Example
Create 5 buttons and add them to the panel that contains them
116
Example
Add the panel to the frame in the southern position
117
Adapter Classes
Many event-listener classes provide multiple methods For example
MouseListener MouseMotionListener
It is not always desirable to define every method in an event listener interface
118
Adapter Classes
For example When a windowed application is terminated
A method named windowClosing is invoked from the interface WindowListener
WindowListener specifies seven window-event handling methods
119
Adapter Classes
In order to avoid implementing all of the listener methods Java provides adapter classes
An adapter class Implements an interface Provides a default implementation
Usually has an empty body Can be extended with specific functionality when
required
120
Adapter Classes
Event Adapter Class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
Implements Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener
121
Example
We add a mouse motion listener and define an instance of a class MouseMotionAdapter to define functionality for the dragging of the mouse. xValue and yValue will record the current position of the mouse
122
Example
The repaint() method causes the frame to be redrawn and this is accomplished by the paint() method
The paint() method draws a small oval at the recorded xValue and yValue
123
Class Exercise
Write Java code to create the interface shown below (do not worry about its functionality)