Chapter 12 - GUI

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 90

Part I

Introduction to GUI Programming


in Java:
Frames, Simple Components, and
Layouts
Corresponds with Chapter 12
 Introduction

 A graphical user interface (GUI) presents a user-


friendly mechanism for interacting with an
application.
 Pronounced “GOO-ee”
 Gives an application a distinctive “look-and-feel.”
 Consistent, intuitive user-interface components give
users a sense of familiarity
 Learn new applications more quickly and use them
more productively.
Elements of GUI Programming

 Components
 Visual objects that appear on the screen
 Layouts
 Control over the positioning of components within a
container
 Events
 Responses to user actions
 Graphics
 Lines, shapes, colors, fonts, etc.

All are encapsulated in Java Classes and Packages


Components
Two categories of Java Component classes:
 AWT – Abstract Windows Toolkit (java.awt package)
 The older version of the components
 Rely on “peer architecture”…drawing done by the OS
platform on which the application/applet is running
 Considered to be “heavy-weight”
 Swing (javax.swing package)
 Newer version of the components
 No “peer architecture”…components draw themselves
 Most are consdered to be “lightweight”

The textbook focuses primarily on Swing classes


GUI Class Hierarchy (AWT)
AWTEvent Container Panel Applet

Font Button Window Frame

FontMetrics Label Dialog FileDialog


TextField
Object Color TextComponent

TextArea
Graphics List

Component Choice

CheckBox

LayoutManager CheckBoxGroup

Canvas

MenuComponent MenuItem Menu

MenuBar
Scrollbar
GUI Class Hierarchy (Swing)
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent Swing Components


in the javax.swing package

Lightweight
Container Classes
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


Container classes can in the javax.swing package

contain other GUI


components.
Lightweight
GUI Helper Classes
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

The helper classes are not Swing Components


JComponent JPanel
subclasses of Component. in the javax.swing package

They are used to describe the


properties of GUI components Lightweight
such as graphics context,
colors, fonts, and dimension.
Swing GUI Components
JCheckBoxMenuItem

JMenuItem JMenu

AbstractButton JButton JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton
JComponent JEditorPane

JTextComponent JTextField JPasswordField

JTextArea

JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider

JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane

JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip

JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner


Creating GUI Objects
// Create a button with text OK
JButton jbtOK = new JButton("OK");
 
// Create a label with text "Enter your name: "
JLabel jlblName = new JLabel("Enter your name: ");
  Label Text Check Radio
field Box Button

Button

// Create a text field with text "Type Name Here" Combo


JTextField jtfName = new JTextField("Type Name Here");
Box
 
// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");
 
// Create a radio button with text red
JRadioButton jrbRed = new JRadioButton("Red");
 
// Create a combo box with choices red, green, and blue
JComboBox jcboColor = new JComboBox(new String[]{"Red",
"Green", "Blue"});
Creating GUI Objects
Example 2
 Example of a GUI: SwingSet3 application
http://www.oracle.com/technetwork/java/javase/
downloads/index.html
 title bar at top contains the window’s title.
 menu bar contains menus (File and View).
 In the top-right region of the window is a set of buttons
 Typically, users press buttons to perform tasks.
 In the GUI Components area of the window is a combo box;
 User can click the down arrow at the right side of the box to select
from a list of items.
Frames
 Frame is a window that is not contained
inside another window.
 Frame is the basis to contain other user
interface components in Java graphical
applications.
 The Frame class can be used to create
windows.
Any use of Swing classes
requires importing javax.swing
package.

Instantiate a swing Frame


object

Call JFrame methods to control visuals and behavior


Set width and height of the frame in pixels
Cause frame to be centered on the screen when displayed
When user closes the window, the application will terminate
This is needed to make the frame actually show up on the screen
This is what a
frame looks like.

Note the title bar,


the content area,
the minimize,
maximize/restore,
and close icons.

Caption in the
title bar was
determined from
the argument to
the constructor.
Frames with Components
 A Frame is a container. Therefore it can contain
other components (like buttons, text fields,
etc.)
 Components are added to the content pane of
a frame.
 The content pane is the grey area in the Frame
window.
 A simplistic way to look at containment is this:
 A JFrame contains:
1. A menu bar
2. A content pane
A Picture of Frame Containment

Actually, there’s more to it than this, but this picture will suffice for now.
Example: adding a component to the content pane of a Frame
1) Declare a 2) Instantiate a button
reference
variable for a
button object.

Note: prior to Java 1.5, you


needed to call
getContentPane() in order to
obtain the frame’s content
pane.
3) Add the button
to the content This is no longer necessary.
pane of the
frame.
Resulting Screen

Here is the button


Layout Managers
 Control the placement of components on the
container.
 This is an alternative to hardcoding the pixel
locations of the components.
 Advantage: resizing the container (frame) will
not occlude or distort the view of the
components.
 Main layout managers:
 FlowLayout, GridLayout, BorderLayout, CardLayout,
and GridBagLayout
Layout Manager Hierarchy

LayoutManager is an interface. All the layout classes implement this interface


FlowLayout
 Places components sequentially (left-to-right) in the order
they were added
 Components will wrap around if the width of the container is
not wide enough to hold them all in a row.
 Default for applets and panels, but not for frames
 Options:
 left, center (this is the default), or right
 Typical syntax: in your Frame class’s constructor
setLayout(new FlowLayout(FlowLayout.LEFT)) OR
setLayout(new
FlowLayout(FlowLayout.LEFT,hgap,vgap))
A Frame class that uses FlowLayout layout manager
A Frame class that uses FlowLayout layout manager

Note: creating a subclass of


JFrame
A Frame class that uses FlowLayout layout manager

Note: it’s common to


make the Frame an
application class by
including a main method.
The main method will
instantiate its own class.
A Frame class that uses FlowLayout layout manager

Swing components are in java.swing package

Layout managers are in java.awt package

The constructor will typically do the following:


1) Set the layout manager for the frame’s content pane
2) Add the components to the frame’s content pane

In this case, the layout is Flow, and 6 Swing components are added
Resizing the frame causes the
components to wrap around when
necessary.
GridLayout
 Arranges components into rows and columns
 In Frame’s constructor:
 setLayout
(new GridLayout(rows,columns))
OR
 setLayout(new

GridLayout(rows,columns,hgap,vgap))
 Components will be added in order, left to right, row by row
 Components will be equal in size
 As container is resized, components will resize accordingly,
and remain in same grid arrangement
A Frame class that uses GridLayout layout manager

Setting the layout manager

Adding components
Resizing the frame causes the
components to resize and maintain
their same grid pattern.
BorderLayout
 Arranges components into five areas: North, South, East, West, and
Center
 In the constructor:
 setLayout(new BorderLayout())
 OR
 setLayout(new BorderLayout(hgap,vgap))
 for each component:
 add (the_component, region)
 do for each area desired:
 BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST,

BorderLayout.NORTH, or BorderLayout.CENTER
 Behavior: when the container is resized, the components will be resized but remain
in the same locations.
 NOTE: only a maximum of five components can be added and seen in this case,
one to each region.
A Frame class that uses BorderLayout layout manager

Setting the layout manager

Adding components to
specific regions
Resizing the frame
causes the
components to
resize and maintain
their same regions.

NOTE: the CENTER region dominates


the sizing.
Using Panels as “Sub-Containers”
 JPanel is a class of special components that can contain
other components.
 As containers, JPanels can have their own layout
managers.
 This way, you can combine layouts within the same
frame by adding panels to the frame and by adding
other components to the panels.
 Therefore, like JFrames, you can use these methods
with JPanels:
 add() – to add components to the panel
 setLayout() – to associate a layout manager for the panel
Testing Panels
This example uses panels to organize
components. The program creates a user
interface for a Microwave oven.
frame
A textfield
p2
A button 12
buttons p1
A Frame class that
contains panels for
organizing
components
A Frame class that
contains panels for
organizing
components

Creating a panel and


setting its layout
A Frame class that
contains panels for
organizing
components

Adding
components to
the panel
A Frame class that
contains panels for
organizing
components
Creating another panel and
setting its layout…note that
this setting layout for the
panel can be done using an
overloaded constructor
A Frame class that
contains panels for
organizing
components

Adding components to the second panel…

NOTE: panel p1 is embedded


inside panel p2!
A Frame class that
contains panels for
organizing
components

Adding a panel and a button to


the frame’s content pane.

Note: the JFrame class’s default


layout manager is Border, so
you if you don’t explicitly call
setLayout() for the frame it will
be Border.
Button in the CENTER region
Panel p2 in the EAST region

Frame has BorderLayout manager


Text field in NORTH region

Panel p1 in the CENTER


region

Panel p2 has BorderLayout manager


Panel p1 has GridLayout manager,
four rows and three columns
Part II
GUI Programming in Java:
Event Handling
& More Components
Corresponds with Chapter 12
Event-Driven Programming
 Procedural programming is executed in
procedural order.

 In event-driven programming, code is


executed upon activation of events.
Events and Listeners
 An event can be defined as a type of signal to the
program that something has happened.

 The event is generated by external user actions such as


mouse movements, mouse button clicks, and
keystrokes, or by the operating system, such as a timer.

 Events are responded to by event listeners


The Delegation Model
Register by invoking
source.addXListener(listener);
Trigger an event
User source: SourceClass listener: ListenerClass
Action
+addXListener(XListener listener)

Keep it a list
XListener
event: XEvent listener1
Invoke listener2
listener1.handler(event) …
+handler(XEvent event)
listener2.handler(event) listenern

listenern.handler(event)

Internal function of the source object


+handler(
XEvent
Event-generating Objects send Events to Listener Objects
Each event-generating object (usually a component) maintains a set of listeners for
each event that it generates.

To be on the list, a listener object must register itself with the event-generating object.

Listeners have event-handling methods that respond to the event.


Event Classes

We will focus on ActionEvent and ListSelectionEvent


Selected User Actions
Source Event Type
User Action Object Generated

Click a button JButton ActionEvent


Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Select an item from a List JList ListSelectionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Any Component MouseEvent
Key released, pressed, etc. Any Component KeyEvent
Java AWT Event
Listener Interfaces
 ActionListener  KeyListener
 AdjustmentListener  MouseListener
 ComponentListener  MouseMotionListener
 ContainerListener
 TextListener
 FocusListener
 WindowListener
 ItemListener
 ListSelectionListener
All are in the java.awt.event or javax.swing.event package
All are derived from EventListener in the java.util package
NOTE: any object that will respond to an event must implement a listener interface.
How to Implement a Listener
Interface
 Use the implements keyword in the class
declaration
 Register the object as a listener for a
component’s event, using the component’s
addXListener method. (where X is the type of
event). (Typically done in constructor)
 Declare and fully define all methods for the
interface that you are implementing
 Requires:
 Complete method signature
 Method body
Selected Event Handlers

Event Class Listener Interface Listener Methods (Handlers)


ActionEvent ActionListener actionPerformed(ActionEvent)

ItemEvent ItemListener itemStateChanged(ItemEvent)

ListSelection ListSelection valueChanged


Event Listener (ListSelectionEvent)
Handling Simple Action Events

The method for


responding to an
Action event.
Implementing the listener
interface

Registering the frame


to be a listener for
action events
generated by the two
buttons
Handling Simple Action Events –
a closer look at the event-handling method

actionPerformed is a method
required for all ActionListeners

An Event object’s getSource()


method returns a reference to
the Component object that
generated the event.
Alternative Approaches to Listening
 Implement the listener with the main application
class, and have the one listener assigned to all
components generating the events
 This is the approach I generally use with my examples
 Advantage: simplicity for beginner programmers
 Disadvantage: event-handler method may require if-statement
or switch with several branches when multiple components
generate the event
 Use inner classes to implement the listeners and create
a different instance as each component’s listener.
 Named inner class or anonymous inner class (This is the
approach used in the textbook most of the time)
 Advantage: no need to test within the listeners for determining
which component sent the event. Each component has its own
dedicated listener
 Disadvantage: harder to understand for novice programmers
Example with
named inner
classes, one for
listening to each
button

Inner class has


direct access to
all members
(even private)
of the outer
class
Example with anonymous
inner classes, one for
listening to each button
Working with JLabel, JTextField,
JTextArea, JList, JComboBox,
and JRadiobutton
JLabel
 Swing class for a non-editable text display
 Typical constructor:
 JLabel(stringValue)
 Other Useful Methods:
 getText() – returns a string containing the
text in the label component
 setText(String) – sets the label component to
contain the string value
JTextField
 Swing class for an editable text display
 Many constructors possible – here’s one:
 JTextField(columnWidth)
 Will instantiate a text field component of the specified width
(width is approximate number of characters visible).
 Some useful methods:
 getText() – returns the text value in the text field
 getSelectedText() – returns the text value that has
been highlighted in the text field
 setText(stringValue) – sets the text value to the
indicated argument
JTextArea
 Swing class for an editable text display
 Many constructors possible – here’s one:
 JTextArea(rowHeight , columnWidth)
 Will instantiate a text area component of the specified width and
height (width is approximate number of characters visible, height
is approximate number of text lines visible)
 Some useful methods:
 getText() – returns the text value in the text field
 getSelectedText() – returns the text value that has
been highlighted in the text field
 setText(stringValue) – sets the text value to the
indicated argument
 append(stringvalue) – appends the text value of the
string to the already existing text in the component
Note use of getText, setText, getSelectedText and append
methods.
JList
 Swing GUI component that presents a list of items
 Many constructors…here’s one:
 JList(sourceArray);
 Produces a ListSelectionEvent
 Handling this event by implementing a ListSelectionListener
 Need to import javax.swing.event package for this
 Some useful methods:
 addListSelectionListener – specify which objects will respond to list
selection event
 setListData – indicate the source of data for this list (e.g. an array)
 getSelectedIndex – identify the current selection from the list (0-based) --
-1 indicates nothing is selected from list.
 setFixedCellHeight and setFixedCellWidth – indicate pixel size of each item
of the list.
JList Example 1: using lists, text fields, labels, and buttons

Implementing listeners
components

List’s data source


JList Example 1: using lists, text fields, labels, and buttons (con’t.)

When array changes, refresh the list

valueChanged is the ListSelectionListener event handler method

Use list index tp get associated


array element
JList Example 2: slightly more complicated…data source is an array of objects

This is the class being used


for the array associated with the JList.

toString is a method
that overrides the
Object class’s method
of the same name.
This determines what
will be displayed in the
JList.
JList Example 2: slightly more complicated…data source is an array of objects
JList Example 2: slightly more complicated…data source is an array of objects
Exception Handling
 This example makes use of Exception
handling
 try/catch format

 NOTE: if the text entered into the numeric


field cannot be parsed into a number, an
Exception is thrown (specifically a
NumberFormatExeption).
Exception Handling Using
try and catch
try{
…….. If code within the try block causes
an error, the program will

}
automatically branch to the catch
block

catch (ExceptionType e){


……..
}
JList Example 2: slightly more complicated…data source is an array of objects

Code in the try block

This may throw an exception

Here we handle the exception


JComboBox
 Swing GUI component that presents a dropdown list of items
 Many constructors…here’s one:
 JComboBox(sourceArray);
 Produces an ActionEvent and an ItemEvent
 You can handle these event by implementing an ActionListener or an
ItemListener
 If you want to handle these events, you need to import
java.awt.event package
 Some useful methods:
 getSelectedIndex – identify the current selection from the list (0-
based) -- -1 indicates nothing is selected from list.
 getSelectedItem – returns the currently selected object from the list.
Since it returns an Object reference, if you want to treat it as string,
you should call toString() for the returned object
 setSelectedIndex – Changes the current selection to whatever the
integer is that is passed as an argument.
 setSelectedItem – sets the currently selected item to whatever the
Object is that is passed as an argument
JRadioButton
 Swing GUI component that presents a radio buttons of options. You
group the options into a ButtonGroup.
 Many constructors…here’s one:
 JRadioButton(Label)
 Since a RadioButton is a button, it produces an ActionEvent. It also
generates a ChangeEvent
 You can handle these event by implementing an ActionListener or an
ChangeListener
 If you want to handle these events, you need to import java.awt.event
package
 Lots of useful methods…here’s three:
 setMnemonic – Specifies a alt-Key alternative for selecting the RadioButton.
 isSelected – returns a boolean value to specify if the button has been
selected
 setSelected(boolean) – allows you to programmatically change the selection
status of a RadioButton
 Put related RadioButtons into a ButtonGroup, so only one will be
selected at a time
 Instantiate the ButtonGroup
 Call the ButtonGroup’s add method to assign RadioButtons
By putting all buttons into a panel, you
can place them all together in the
same region of the frame’s
BorderLayout

By putting all buttons into a


ButtonGroup, you ensure that only one
will be selected at a time
This code causes the RadioButtons to
generate ActionEvents that the frame
will listen to

Via setMnemonic, you allow Alt-1, Alt-


2 and Alt-3 to select the appropriate
RadioButtons
A component’s action command is
usually its label, although you can
change this

The setSelected method can be


used to programmatically change
the current RadioButton selection

The isSelected method can be used


to determine if a RadioButton is
selected

You might also like