Chapter 17 : Building a Graphical User Interface

Download Report

Transcript Chapter 17 : Building a Graphical User Interface

An Introduction to
Programming and Object
Oriented Design using Java
3rd Edition. Dec 2007
Jaime Niño
Frederick Hosch
Chapter 17 : Building a Graphical User Interface
Application interfaces
 algorithm-driven
 Application is active
 Application determines exactly what information it
needs from environment, and when to get it.
 The text-based interfaces are algorithm driven.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
1
Application interfaces
 event-driven
 Application it is passive.
 Application waits for an event to happen in the
environment
 When an event occurs, the application responds to
the event, and then waits for the next event.
 Applications with a graphical, window-based user
interface are almost always event driven
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
2
Event-driven applications
 A window-based system, has windowing
managing display and event detection.
system
 A Java application interacts with native windowing
system through AWT components.
 Application communicates with native windowing system
to create a display.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
3
Event-driven applications
 Events occurring in display are
 awaited for by application
 detected by the native windowing system
 delivered to application.
 responded-to by application.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
4
An introduction to Swing: Components
 Basic (atomic) components,
 present information to or get information from user.
 Examples:
button, label, text field,editor pane,
combo box.
 Containers
 hold and position other components.
 Example: JFrame, JPanel.
 top-level container
 contains all of the visual components of a GUI
 provides the screen real estate used by application.
 Intermediate containers
 used to organize and position GUI components.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
5
JComponent
 Subclass of java.awt.Component.
 Component properties, obtained with queries:
public
public
public
public
public
Color getForeground ();
Color getBackground ();
Point getLocation ();
Dimension getSize ()
Font getFont ();
 And set via corresponding methods:
public void setForeground (Color fg);
public void setBackground (Color bg);
public void setLocation (Point p);
public void setSize (Dimension d);
public void setFont (Font f);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
6
Other basic classes
 AWT classes defined in the package java.awt
 Color, ( an immutable class)
 Point,
 Dimension,
 Font
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
7
Basic components to gather input
 JButton
 JCheckBox toggled on/off button displaying state to user.
 JRadioButton a toggled on/off button displaying its state
to user.
 JComboBox a drop-down list with optional editable text
field. The user can key in a value or select a value from
drop-down list.
 Jlist allows user to select one or more items from a list.
 Jmenu popup list of items from which the user can select.
 Jslider lets user select a value by sliding a knob.
 JTextField area for entering a single line of input.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
8
Basic components to present information
 Jlabel contains text string, an image, or both.
 JProgressBar communicates progress of some work.
 JToolTip describes purpose of another component.
 Jtree a component that displays hierarchical data in
outline form.
 Jtable a component user to edit and display data in a
two-dimensional grid.
 JTextArea, JTextPane, JEditorPane
 define multi-line areas for displaying, entering, and
editing text.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
9
Swing components
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
10
Swing components
A JTree
A JTable
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
11
Container
 Component that can contain other components and
containers.
Component
Container

has
JCom ponent
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
12
Intermediate components
 Used to organize and position other components.
 JPanel used for collecting other components.
 JScrollPane provides view with scroll bars.
 JSplitPane divides two components graphically.
 JTabbedPane lets the user switch between a group of
components by clicking on a labeled tab;
 JToolBar used for displaying a set of commonly used
controls.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
13
Example of component organization
 The following creates a JPanel and adds two buttons,
labeled “on” and “off.”
JPanel p = new JPanel();
p.add(new JButton("on"));
p.add(new JButton("off"));
 Wherever this panel is used, it will present the two
buttons.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
14
Top-level container
 It’s not contained in any other container.
 provide screen area where other components can
display themselves.
 JApplet, JDialog, JFrame, and JWindow are
commonly used as top-level containers.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
15
JFrame
 It’s a window with title, border, (optional) menu bar and
user-specified components.
 It can be moved, resized, iconified.
 It is not a subclass of JComponent.
 Delegates responsibility of managing user-specified
components to a content pane, an instance of JPanel.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
16
Jframe
Jframe
Jframe internal structure
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
17
JFrame
 To add a component to a JFrame, add it to the content
pane:
JFrame f = new JFrame("A Frame");
JButton b = new JButton("Press");
Container cp = f.getContentPane();
cp.add(b)
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
18
JFrame components are in its content pane
JFrame
content pane
Container

Component
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
19
Heavyweight and lightweight components
 Heavyweight components
 Instances of classes JApplet, JDialog, JFrame, and
JWindow.
 Created by association to a native GUI component
part of the native windowing system.
 Their look and feel depends on the native GUI
component.
 Lightweight components
 Any other Swing component.
 They are completely implemented in Java.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
20
A Simple app displaying a JFrame
import javax.swing.*;
public class DisplayFrame {
public static void main (String[] args) {
JFrame f = new JFrame("A Frame");
//… components are added to its content frame.
f.setSize(300,200);
f.setVisible(true);
}
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
21
Sequential/Concurrent programming
 A thread is a sequence of instructions being executed by
the processor.
 Sequential programming: So far programs consisted of a
single thread, which executes the sequence of actions in
the main method (main thread).
 Concurrent programming: A program can contain
several threads each executing independent sequences
of actions.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
22
Sequential/Concurrent programming
 Event-dispatching thread: executes all the code that
involves repainting components and handling events.
 After the JFrame has been made visible, the main
thread should not perform actions that affect or depend
on the state of the user interface.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
23
LayoutManager
 Responsible for positioning and sizing components
added to a container.
 Each container is associated with a LayoutManager.
 Setting and accessing Container’s layout manager:
public LayoutManager getLayout();
public void setLayout (LayoutManager manager);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
24
LayoutManager classes
 FlowLayout
bottom.
lays out components left to right, top to
 BorderLayout lays out up to five components, positioned
“north,” “south,” “east,” “west,” and “center.”
 GridLayout lays out components in a two-dimensional grid.
 CardLayout
displays components one at a time from
a preset deck of components.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
25
LayoutManager classes
 GridBagLayout lays out components vertically and
horizontally according to a specified set of constraints.
 BoxLayout lays out components in either a single
horizontal row or single vertical column.
 OverlayLayout components are laid out on top of each
other.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
26
Default layout managers
 A FlowLayout lays out components in order added to
container.
 In BorderLayout, a component’s position is specified by
a second argument to add.
 Jpanel default layout manager: FlowLayout.
 JFrame’s
content
BorderLayout.
Dec 2007
pane
default
layout
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
manager:
27
Component layout figures
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
28
Component layout figures
CardLayout view 1
Dec 2007
CardLayout view 2
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
29
Events and components
 Events are objects.
 Events: subclasses of abstract class java.awt.AWTEvent.
 Components generate events.
 An event object knows event source and other relevant
information about the event.
 Given an event, to query for its component’s source:
public Object getSource();
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
30
Listener or Event handler
 Listener: An object interested in being notified when an
event occurs in a given component.
 A Listener object registers with a component to be
notified of events generated by it.
 Listener must implement the event listener interface
associated with events for which it registered.
 Programming a handler for an event consists of
implementing the interface associated with the event
type.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
31
GUI programming example
 Program an application that displays a button. When the
button is pressed, its foreground and background colors
are swapped.
 Design: extended the class JFrame with OnOffSwitch,
and its constructor builds the frame containing the
button.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
32
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class OnOffSwitch extends JFrame {
public OnOffSwitch () {
super("On/Off Switch"); // frame title
JButton button = new JButton("On/Off");
button.setForeground(Color.black);
button.setBackground(Color.white);
this.getContentPane().add(button,
BorderLayout.CENTER);
}
}//end of OnOffSwitch
public class OnOffTest {
public static void main (String[] args) {
OnOffSwitch frame = new OnOffSwitch();
frame.setSize(300,200);
frame.setVisible(true);
}
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
33
Program does not work
 Pressing the button has no effect at all.
 When
the
ActionEvent.
button
is
pressed,
it
generates
an
 Have not “programmed” the user interface to respond
to that event.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
34
Programming the gui: an ActionListener for JButton
 Implement a listener to handle event generated by
JButton instance.
 If user presses button, it generates an ActionEvent.
 To do:
 Define a class, Switcher, that implements
ActionEvent.
 Register an instance of Switcher with the Jbutton
instance.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
35
Revision of OnOffSwitch to create a Switcher listener
and register it with JButton
public OnOffSwitch () {
super("On/Off Switch"); // frame title
// create button and set its colors
JButton button = new JButton("On/Off");
button.setForeground(Color.black);
button.setBackground(Color.white);
// create and register button’s listener:
button.addActionListener(new Switcher());
// add button to JFrame’s content pane:
this.getContentPane().add(
button, BorderLayout.CENTER);
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
36
Defining Switcher
class Switcher implements ActionListener {
public void actionPerformed (ActionEvent e) {
Component source = (Component)e.getSource();
Color oldForeground = source.getForeground();
source.setForeground(source.getBackground());
source.setBackground(oldForeground);
}
}
OnOffSwitch
has
JButton
Switcher
Dec 2007
listens to
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
37
Programming the JFrame close
 To terminate the program need to program a window
listener to close the window.
 A window listener must implement the 7 methods in
WindowListener interface.
 We only want to implement 2 of those methods:
void windowClosed (WindowEvent e)
void windowClosing (WindowEvent e)
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
38
Adapter classes: WindowAdapter
 Java provides a collection of abstract event adapter
classes.
 These adapter classes implement listener interfaces with
empty, do-nothing methods.
 To implement a listener class, we extend an adapter
class and override only methods needed.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
39
Terminator class
//implements window events to close a window
class Terminator extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window w = e.getWindow();
w.dispose();
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
40
Revision of OnOffSwith to create a Terminator and
register with JFrame
public OnOffSwitch () {
super("On/Off Switch"); // frame title
this.addWindowListener(new Terminator());
// create button and set its colors
JButton button = new JButton("On/Off");
button.setForeground(Color.black);
button.setBackground(Color.white);
// create and register button’s listener:
button.addActionListener(new Switcher());
// add button to JFrame’s content pane:
this.getContentPane().add(
button, BorderLayout.CENTER);
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
41
Basic GUI programming review
 To a JFrame instance
 add components comprising the interface.
 Program a Terminator class to allow user to close
window.
 For every GUI component that generates events for
which your application needs to react to:
 Define a class that implements the Listener interface
for desired events.
 Instantiate and register Listener class with the
component that generates desired events.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
42
Building GUIs
 Use JPanel as a decomposition tool for complex views.
 A standard technique.
 Provides more flexibility;
 JPanel can be added to other structures to expand or
modify application.
 Build app view on a JPanel and add to a JFrame content
pane.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
43
Building GUIs
 Components can have borders to give them desired
looks.
 The JComponent
component:
method
adds
a
border
to
a
public void setBorder (Border border)
 Standard
borders
are
javax.swing.BorderFactory.
Dec 2007
obtained
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
from
the
class
44
MenuBar and Menu
 A menu offers options to user.
 Menus are not generally added to user interface.
 menu usually appears either in a menu bar or as a popup
menu.
 A JFrame often has a menu bar containing many menus;
and each menu can contain many choices.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
45
MenuBar and Menu
 Menu bar can be added to a JFrame with the method
setJMenuBar:
JFrame window = new JFrame("Some Application");
JMenuBar menuBar = new JMenuBar();
window.setJMenuBar(menuBar);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
46
Menu
 Menus are JMenu instances and added to menu bar:
JMenu batter = new JMenu("Batter");
menuBar.add(batter);
 Menu choices are JMenuItem instances, and are added
to menu:
JMenuItem swing = new JMenuItem("Swing");
JMenuItem take = new JMenuItem("Take");
JMenuItem bunt = new JMenuItem("Bunt");
batter.add(swing);
batter.add(take);
batter.add(bunt);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
47
Menubar and Menu
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
48
JMenuItem listener
 When the user selects an item, the JMenuItem selected
generates an ActionEvent.
 Implement an ActionListener for each JMenuItem to
program menu events.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
49
Java code examples for widgets
 Visit:
 http://java.sun.com/docs/books/tutorial/uiswing/components/
 And choose choice: How to …
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
50
Dialog
 A window to present information or gather input from
user.
 For standard dialogs use:JOptionPane, JFileChooser, and
JColorChooser
 For custom dialogs use JDialog.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
51
Dialog
 Every dialog
 Has owner, a frame.
 It’s destroyed if owner is destroyed,
 disappears from the screen while owner is iconified.
 Two kinds of dialogs
 modal : User input to all other windows is blocked
when a modal dialog is visible.
 non-modal : dialogs for which you must use JDialog.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
52
JOptionPane showMessageDialog
 Used to create simple, standard dialogues.
public static void showMessageDialog (
Frame owner
Component parentComponent,
String message to be displayed
Object message,
String title,
Window’s title
int messageType,
int value indicating style of message
Icon icon
icon to be displayed in dialog
);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
53
JOptionPane showInputDialog
 Used to get input from user. It gets a String from user,
using either a text field or a combo box.
 Parameters are the same as in showMessageDialog.
 A simpler variants of method is specified as
public static String showInputDialog (
Component parentComponent, Object message)
 When user presses “OK” button:
 contents of text field is returned or null if user presses “Cancel”
or closes window.
 Contents is String. Requesting a number from user, you must
validate and convert String to appropriate type of value.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
54
showInputDialog
String response =
JOptionPane.showInputDialog(frame, “Message Type”);
int value = convertToInt(response);
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
55
JOptionPane method showConfirmDialog
 The showConfirmDialog generates a two or three
button window.
 The two button provides “Yes” and “No” or ‘OK” and
“Cancel” buttons.
 The three button, “Yes,” “No,” and “Cancel” buttons.
 The method returns an int indicating the user’s
response. Possible return values include
JOptionPane.YES_OPTION,
JOptionPane.OK_OPTION,
JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION,
and if user closes window,
JOptionPane.CLOSED_OPTION.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
56
Show confirm dialog
int response =
JOptionPane.showConfirmDialog(frame,
“Take over the world?”,
“The Brain”, JOptionPane.YES_NO_OPTION);
if (response == YES_OPTION) …
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
57
FileChooser and JColorChooser dialogs
 JFileChooser : mechanism for user to select a file.
JFileChooser directory = new JFileChooser();
directory.setCurrentDirectory(new File(“.”));
directory.showOpenDialog(this); //open dialog.
File file = directory.getSelectedFile();
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
58
FileChooser and JColorChooser dialogs
 JColorChooser presents a pane of controls that allow a
user to select and manipulate a color.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
59
JDialog
 Used to create custom dialog windows.
 A Jdialog
 a top-level window.
 has an owner, generally a frame.
 It delegates component management to a content
pane, to which components are added.
 It’s displayed by invoking its setVisible method with
an argument of true, and is hidden by invoking its
setVisible method with an argument of false
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
60
JDialog
 A typical constructor is specified as follows:
public JDialog (Frame owner, String title,
boolean modal)
 Provides an object to create custom views to get or
present data.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
61
Graphics
 Every component has a graphics context.
 The Graphics object has methods for drawing text,
images, and geometrical figures on components.
 drawLine,
 drawImage,
 drawRect,
 drawString,
 fillRect, etc.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
62
Drawing a triangle
 A JPanel can be used as a canvas to draw on.
 JPanel defines an integer coordinate system with
coordinates ranging from (0,0) in the upper left to
(width-1, height-1) in the lower right.
 Units are pixels.
 To draw on a JPanel, we override the method
painComponent.
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
63
Drawing a triangle
class TrianglePanel extends JPanel {
…
public void paintComponent (Graphics g) {
super.paintComponent(g);
g.drawLine(10,10,10,80);
g.drawLine(10,80,110,80);
g.drawLine(110,80,10,10);
}
}
Dec 2007
NH-Chapter 17:An Introduction To Programming
And Object Oriented Design Using Java
64