Y. Daniel Liang 1 Graphical User Interfaces Chapter 12.
-
Upload
barbra-bryant -
Category
Documents
-
view
249 -
download
3
Transcript of Y. Daniel Liang 1 Graphical User Interfaces Chapter 12.
Y. Daniel Liang 1
Graphical User Interfaces
Chapter 12
Y. Daniel Liang 2
Programs
•MyFrame•MyFrameWithComponents•CenterFrame•ShowFlowLayout•ShowGridLayout•TestPanels•SimpleEventsDemo Two classes within one file• SimpleEvent DemoAnonymousInnerClass
Y. Daniel Liang 3
Programs•ShowInnerClass• GuiNew See the object code for the inner classes•TestActionEvent Team 4•TestActionEventNew Team4•ButtonDemo
•ViewFile Team 3 signature.txt
•CreateMenus Team # 1 and 2 new.gif and open.gif
Y. Daniel Liang 4
Programs•TestPanel Team #5• GuiNew See the object code for the inner classes•TestActionEvent Team 4•TestActionEventNew Team4•ButtonDemo
•ViewFile Team 3 signature.txt
•CreateMenus Team # 1 and 2 new.gif and open.gif
Y. Daniel Liang 5
Graphical User Interfaces -- Introduction
Users have become accustomed to using a graphical user interface (GUI) through which they interact with a program
Java provides strong support for building GUIs through the java.awt and javax.swing packages
This section focuses on:– GUI components– event-driven programming– containers and component hierarchies– layout managers
Y. Daniel Liang 6
GUI Elements The key elements of a Java graphical user
interface are:– GUI components– layout managers– event processing
GUI components, such as text fields and buttons, are the screen elements that a user manipulates with the mouse and keyboard
Layout managers govern how the components appear on the screen
Events signal important user actions, like a mouse click
Y. Daniel Liang 7
SwingGraphic User Interfaces (GUI)
Objectives: See GUI Components Create user interfaces using frames, panels, and plain GUI components
Understand the role of layout managers
To use the FlowLayout, GridLayout, and BorderLayout managers
To use JPanels as subcontainers
Y. Daniel Liang 8
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: ");
// Create a text field with text "Type Name Here"JTextField jtfName = new JTextField("Type Name Here"); // Create a check box with text boldJCheckBox jchkBold = new JCheckBox("Bold"); // Create a radio button with text redJRadioButton jrbRed = new JRadioButton("Red"); // Create a combo box with choices red, green, and blueJComboBox jcboColor = new JComboBox(new String[]{"Red", "Green", "Blue"});
Button
Label Text field
Check Box
Radio Button
Combo Box
Y. Daniel Liang 9
GUI Components //Create a button with text hello JButton jbtHello = new JButton(“Hello ”);
//Create a label with text “Enter your age: “); JLabel jlblAge = new JLabel(“Enter your age: “);
//Create a text field with text “Type age here: “ JTextField jtfAge = new JTextField (“Type age here: “);
Y. Daniel Liang 10
GUI Components //Create a check box with text bold JCheckBox jchkBold = new JCheckBox(“Bold”);
//Create a radio button with text blue JRadioButton jrbBlue = new JRadioButton(“Blue”);
//Create a combo box with options red, green, and blue JComboBox jcoColor = new JComboBox(new String[]
{“Red”, “Green”, “Blue”});
Y. Daniel Liang 11
Swing versus AWT First GUI classes were bundled in a library known as
Abstract Windows Toolkit (AWT)
Heavy weight components -AWT components Platform-specifics- more error-prone
A peer-based approach relies heavily on the underlying platform (operating system)
Will slowly fade away- not recommended for new applications
Y. Daniel Liang 12
Light Weight Components -Swing Less dependent on the target platform Uses less of the native GUI resources
Replaced AWT components with a more robust, versatile, and flexible library known as Swing components
Swing components are painted directly on canvas using Java code
except for
components that are subclasses of java.awt.Window or java.awt.Panel, which must be drawn using native GUI on a specific platform
Y. Daniel Liang 13
Swing GUI Components contd
The name of Swing components are prefixed with a J Examples:
JButton JLabel JTextField JCheckBox JRadioButton JComboBox
These are subclasses of JComponent
Y. Daniel Liang 14
Swing GUI Classes Classified Into Three Groups
Container classes Helper Classes Component Classes
Y. Daniel Liang 15
Containers
Component
Container
WindowPanel
DialogFrameApplet
JComponent(Base for Swing
Components)
JApplet JFrame JDialog
Y. Daniel Liang 16
Swing GUI Container Classes
Container classes: JFrame JPanel JApplet
-Subclasses of Component-Used to contains other components-Uses Layout managers to position and place components in a container in the desired location
Y. Daniel Liang 17
Helper Classes Graphics Color Font FontMetrics Dimension Layout Manager
-Not subclasses of Component -Used by components and containers to draw and
place objects -The helper classes are in the java.awt packages
Y. Daniel Liang 18
Frames
To create a user interface (UI), you need to
create either a frame or an applet to hold the
user-interface components
For Swing GUI programs, use JFrame class to create windows.
Y. Daniel Liang 19
Creating Frames
RunRun
import javax.swing.*;public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }
}
MyFrameMyFrame
Y. Daniel Liang 20
Content Pane of A Frame
A frame’s content pane is the section of the frame that excludes the title and menu bars and the border
The content pane is used to display the text images, etc.
Y. Daniel Liang 21
Add Components to a Frame contd.
JDK 1.5 allows you to place components to the content pane by invoking a frame's add() method. This new feature is called
content pane delegation. Strictly speaking, a component is added into the content pane of a frame.
But for simplicity, we say that a component is added to the frame.
Y. Daniel Liang 22
Content Pane Delegation in JDK 1.5// Add a button into the frameframe.getContentPane().add( new JButton("OK"));
RunRunMyFrameWithComponentsMyFrameWithComponents
Title bar
Content pane
// Add a button into the frameJButton jbtOK = new JButton("OK"); frame.add(jbtOK);
Y. Daniel Liang 23
JFrame Class
javax.swing.JFrame
+JFrame()
+JFrame(title: String)
+getSize(width: int, height: int): void
+setLocation(x: int, y: int): void
+setVisible(visible: boolean): void
+setDefaultCloseOperation(mode: int): void
+setLocationRelativeTo (c: Component): void
Creates a default frame with no title.
Creates a frame with the specified title.
Specifies the size of the frame.
Specifies the upper-left corner location of the frame.
Sets true to display the frame.
Specifies the operation when the frame is closed.
Sets the location of the frame relative to the specified component. If the component is null, the frame is centered on the screen.
Y. Daniel Liang 24
Center a Frame
Run CenterFrame.java
Y. Daniel Liang 25
Layout Managers
Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems.
The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container.
Layout managers are set in containers using the setLayout(LayoutManager) method in a container.
Y. Daniel Liang 26
Layout Managers
There are five predefined layout managers in the java.awt package:– flow layout– border layout– card layout– grid layout– grid bag layout
Each container has a particular layout manager associated with it by default
A programmer can also create custom layout managers
Y. Daniel Liang 27
Three Simple and Useful Layout Managers
FlowLayout GridLayout BorderLayout
Each is an interface –whose instances specify
how components are arranged in a container
Y. Daniel Liang 28
Layout Manager -FlowLayout
1 2
3
4 5 6
Y. Daniel Liang 29
The FlowLayout Class
java.awt.FlowLayout
-alignment: int
-hgap: int
-vgap: int
+FlowLayout()
+FlowLayout(alignment: int)
+FlowLayout(alignment: int, hgap: int, vgap: int)
The alignment of this layout manager (default: CENTER).
The horizontal gap of this layout manager (default: 5 pixels).
The vertical gap of this layout manager (default: 5 pixels).
Creates a default FlowLayout manager.
Creates a FlowLayout manager with a specified alignment.
Creates a FlowLayout manager with a specified alignment, horizontal gap, and vertical gap.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Y. Daniel Liang 30
Layout Managers (FlowLayout) Provides a level of abstraction that automatically maps your user interface on all windows systems
Provides platform independence
The FlowLayout manager arranges the components in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started.
Run ShowFlowLayout.java
Y. Daniel Liang 31
FlowLayout Another ExampleStopped Here mon, 6/22/09
Write a program that adds three labels and text fields into the content pane of a frame with a FlowLayout manager.
ShowFlowLayoutNewShowFlowLayoutNew RunRun
Y. Daniel Liang 32
The ShowFlowLayoutNew.java
See the program. It is the preferred style of creating GUI applications for these three reasons:
1.Creating a GUI application means creating a frame, so it is natural to define a frame to extend JFrame.
2. The frame may be further extended to add new components or functions
3. The class can be easily reused. For example, you can create multiple frames by creating multiple instances of the class
Y. Daniel Liang 33
The ShowFlowLayoutNew.java contd.
Using one style consistently makes programs easy to read and maintain.
1.From now on, most of the GUI main classes will extend the JFrame class.
2. The constructor of the main class will construct the user interface.
3.The main method will create an instance of the main class and then display the frame
4. Use a layout manager to place components in a frame.
Y. Daniel Liang 34
Layout Management Classes
Container
JPanel
“Interface”Layout
Manager
GridLayout
To set a layout manager, pick the appropriate layout managerclass and add it to the container: JPanel panel = new JPanel (); panel.setLayout(new GridLayout(4,3)); // 4 rows and 3 //columns
Y. Daniel Liang 35
Layout Manager -GridLayout
1 2 3
4 5 6
7 8 9
10 11 12
Y. Daniel Liang 36
Layout Manager (GridLayout)
The GridLayout manager arranges the components
in the container into the cells of a grid. The
components are placed in the grid from left to right,
row by row.
Run ShowGridLayout.java
Y. Daniel Liang 3737
GridLayout Example
Rewrite the program in the preceding example using a GridLayout manager instead of a FlowLayout manager to display the labels and text fields.
ShowGridLayoutNewShowGridLayoutNew RunRun
Y. Daniel Liang 38
The GridLayout Class
java.awt.GridLayout
-rows: int
-columns: int
-hgap: int
-vgap: int
+GridLayout()
+GridLayout(rows: int, columns: int)
+GridLayout(rows: int, columns: int, hgap: int, vgap: int)
The number of rows in this layout manager (default: 1).
The number of columns in this layout manager (default: 1).
The horizontal gap of this layout manager (default: 0).
The vertical gap of this layout manager (default: 0).
Creates a default GridLayout manager.
Creates a GridLayout with a specified number of rows and columns.
Creates a GridLayout manager with a specified number of rows and columns, horizontal gap, and vertical gap.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Y. Daniel Liang 39
Layout Manager -BorderLayout
NORTH
WEST CENTER EAST
SOUTH
Y. Daniel Liang 40
Layout Manager (BorderLayout)
The BorderLayout manager divides the window into five areas: East, South, West, North, and Center. You can place one (or no components) in an area. The order in which the components are placed is not important, because you always tell the container in which area a component is placed.
Y. Daniel Liang 41
BorderLayout Example
ShowBorderLayoutShowBorderLayout RunRun
Y. Daniel Liang 42
The BorderLayout Class
java.awt.BorderLayout
-hgap: int
-vgap: int
+BorderLayout()
+BorderLayout(hgap: int, vgap: int)
The horizontal gap of this layout manager (default: 0).
The vertical gap of this layout manager (default: 0).
Creates a default BorderLayout manager.
Creates a BorderLayout manager with a specified number of horizontal gap, and vertical gap.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Y. Daniel Liang 43
GridBag Layout
Designed as a two-dimensional grid of columns and rows
However, not all cells in the grid are the same size Components may span multiple columns and rows Each component in a grid bag layout is associated
with a set of constraints, defined by the GridBagConstraints class
A grid bag layout is the most versatile, and most complex, of the predefined layout managers
Y. Daniel Liang 44
Use Panels as Subcontainers
You can divide a window into panels.
Panels act as subcontainers to group user –interface
components
Can add the buttons in one panel, and then add the
panel into the frame.
JPanel is the swing version of Panel
Y. Daniel Liang 45
Use Panels as Subcontainers contd.
new JPanel () will create a panel with a default
FlowLayout manager
OR
new JPanel (LayoutManager) to create a panel with the
specified layout manager
Use the add (Component) method to add a component
to the panel
Y. Daniel Liang 46
Use Panels as ContainersThe following code creates a panel and adds a button to it: JPanel panel2 = new JPanel();panel2.add(new JButton(“OK”));
By default, JPanel uses the FlowLayout. manager
Panels can be placed inside a frame or inside another panel.The following statement places panel panel2 into frame frame2:
Frame2.add(panel2);
Y. Daniel Liang 47
Use Panels as ContainersNote:
To add a component to JFrame, you actually add it to the
content pane of JFrame.
Prior to JDK 1.4
frame.getContentPane().add(new JButton("OK"));
See program : MyFrameWithComponents.
To add a component to a panel, you add it directly to the panel
using the add method.
Y. Daniel Liang 48
Testing Panels Example
This example uses panels to organize components. The program creates a user interface for a Microwave oven.
TestPanelsTestPanels RunRun
A button
A textfield
12
buttons
frame
p2
p1
Y. Daniel Liang 49
Use Panels as Subcontainers
JPanel class can be used for drawing graphics,
displaying text, and viewing images. Although
you may draw things directly on a frame or an
applet, it is recommended that you contain your
drawings in a canvas, so that they do not
interfere with other components.
SKIP
Y. Daniel Liang 5050
Common Features of Swing Components
java.awt.Container
+add(comp: Component): Component
+add(comp: Component, index: int): Component
+remove(comp: Component): void
+getLayout(): LayoutManager
+setLayout(l: LayoutManager): void
+paintComponents(g: Graphics): void
Adds a component to the container.
Adds a component to the container with the specified index.
Removes the component from the container.
Returns the layout manager for this container.
Sets the layout manager for this container.
Paints each of the components in this container.
java.awt.Component
-font: java.awt.Font
-background: java.awt.Color
-foreground: java.awt.Color
-preferredSize: Dimension
-visible: boolean
+getWidth(): int
+getHeight(): int
+getX(): int
+getY(): int
The font of this component.
The background color of this component.
The foreground color of this component.
The preferred size of this component.
Indicates whether this component is visible.
Returns the width of this component.
Returns the height of this component.
getX() and getY() return the coordinate of the component’s upper-left corner within its parent component.
javax.swing.JComponent
-toolTipText: String
-border: javax.swing.border.Border
The tool tip text for this component. Tool tip text is displayed when the mouse points on the component without clicking.
The border for this component.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Y. Daniel Liang 51
Chapter 14
Y. Daniel Liang 52
Programs•TestActionEvent•TestWindowEvent•TestMultipleListener•ShowInnerClass•SimpleEventDemoInnerClass•SimpleEventDemo
•Anonymous???•InnerClass????
Y. Daniel Liang 53
Objectives
To start with event-driven programming with a simple example (§14.1).
To explain the concept of event-driven programming (§14.2).
To understand events, event sources, and event classes (§14.2).
To declare listener classes and write the code to handle events (§14.3).
To register listener objects in the source object (§14.3).
To understand how an event is handled (§14.3).
To write programs to deal with ActionEvent (§14.3).
Y. Daniel Liang 54
Event Driven Programming All the programs that we have written were
object-oriented programs that executed in a procedural order.
We used decision and loop statements to control the flow of execution. The program, itself, dictated the flow of execution
Y. Daniel Liang 55
Event Driven Programming Java graphic programming is event driven.
Codes are executed when an event occurs –
An event is defined as a signal to the program that something has occurred.
For example, click a button, close a window, or move a mouse, press a key on the keyboard, and so on
Y. Daniel Liang 5656
Taste of Event-Driven Programming
The example displays a button in the frame. A message is displayed on the console when a button is clicked.
SimpleEventDemoSimpleEventDemo
RunRun
Y. Daniel Liang 57
Events 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 clicks, and keystrokes, or by the operating system, such as a timer.
The component on which an event is fired or generated is called the source object.
Y. Daniel Liang 58
Event Classes
An event is an object of the EventObject class.
Y. Daniel Liang 59
User Action Source Object Event Type(Event Class)Generated
Click a button JButton Action Event
Change Text JTextComponent TextEvent
Press return on a text field
JTextField Action Event
Select a new item JComboBox ItemEventActionEvent
Select items(s) JList ListSelectionEvent
Click a check box JCheckBox ItemEventActionEvent
Click a radio button JRadioButton ItemEventActionEvent
Select a menu item JMenuItem Action Event
Window opened, closed,iconified, deiconified,or closing
Window WindowEvent
Y. Daniel Liang 60
Event InformationAn event object contains whatever properties are pertinent to the event.
You can identify the source object of the event using the getSource() instance method in the EventObject class.
The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. Table 14.1 lists external user actions, source objects, and event types generated.
Y. Daniel Liang 61
Table 14.1 Selected User ActionsStop here wed, 6/24/09
Source Event TypeUser 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
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
Y. Daniel Liang 62
Event Class
Listener
Interface Listener Method (Handler)
ActionEvent ActionListener actionPerformed(ActionEvent e)
ItemEvent ItemListener itemStateChange(ItemEvent e)
WindowEvent WindowListener windowClosing(WindowEvent e)
windowOpened(WindowEvent e)
windowIconified(WindowEvent e)
windowDeiconified(WindowEvent
e)
windowClosed(WindowEvent e)
windowActivated(WindowEvent e)
windowDeactivated(WindowEvent
e)
Y. Daniel Liang 63
Iconifying means to substitute a small icon on the desktop for the window
Deiconfying means just the opposite
Y. Daniel Liang 64
Inner Class Listeners
A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class.
Y. Daniel Liang 65
Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an inner class to make programs simple.
An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.
ShowInnerClassShowInnerClass
Y. Daniel Liang 6666
Inner ClassesRun OuterClass.java, cont. public class Test {
... } public class A { ... }
public class Test { ... // Inner class public class A { ... } }
(a)
(b)
// OuterClass.java: inner class demo public class OuterClass { private int data; /** A method in the outer class */ public void m() { // Do something } // An inner class class InnerClass { /** A method in the inner class */ public void mi() { // Directly reference data and method // defined in its outer class data++; m(); } } }
(c)
Y. Daniel Liang 6767
Inner Classes (cont.) Inner classes can make programs simple
and concise.
An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class.
For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class.
Y. Daniel Liang 6868
Inner Classes (cont.)
An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class.
An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class
Y. Daniel Liang 69
Revising SimpleEventDemo Using Inner Classes
SimpleEventDemoInnerClassSimpleEventDemoInnerClass
RunRun
Y. Daniel Liang 70
Anonymous Inner Classes An anonymous inner class must always extend a superclass or
implement an interface, but it cannot have an explicit extends or implements clause.
An anonymous inner class must implement all the abstract methods in the superclass or in the interface.
An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object().
An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class.
Y. Daniel Liang 71
Anonymous Inner Classes (cont.)
Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows:
new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary}
Y. Daniel Liang 72
Anonymous Inner Classes (cont.)
public class SimpleEvent DemoAnonymousInnerClass extends Jframe{ public SimpleEvent DemoAnonymousInnerClass () { JButton jbtOK = new JButton (“OK”); Set Layout (new FlowLayout()); add (jbtOK);
// Create and register anonymous inner class listener jbtOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("It is OK"); } });}
Y. Daniel Liang 73
Revising SimpleEventDemo Using Anonymous Inner Classes
SimpleEventDemoAnonymousInnerClassSimpleEventDemoAnonymousInnerClass
RunRun
Y. Daniel Liang 74
Example: Handling Simple Action Events
Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked.
TestActionEventTestActionEvent
RunRun
Y. Daniel Liang 75
Interaction Between Source and Listener
jbtOK: JButton btListener: ButtonListener
1. addActionListener
: TestActionEvent jbtCancel: JButton
2. addActionListener
3. actionPerformed
4. actionPerformed
1. jbtOK registers btListener by invoking addActionListener(btListner).
2. jbtCancel registers btListener by invoking addActionListener(btListner).
3. jbtOK invokes btListener’s actionPerformed method to process an ActionEvnet.
4. jbtCancel invokes btListener’s actionPerformed method to process an ActionEvent.
Y. Daniel Liang 76
Example: Handling Window Events
TestWindowEventTestWindowEvent RunRun
Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.
Y. Daniel Liang 7777
Example: Multiple Listeners for a Single Source
TestMultipleListenerTestMultipleListener RunRun
Objective: This example modifies Listing 14.1 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listener. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.
Y. Daniel Liang 78
Event-Driven ProgrammingSteps to design and implement a GUI:1. Identify the actions (methods) that your program needs to
perform -withdraw funds from savings account
2. Identify each input that is needed for the action – withdrawal amount
3. Identify the outputs that you must display for each action – the current amount
4. Supply the user interface components – buttons for action text fields to hold input labels for output
Y. Daniel Liang 79
Event-Driven ProgrammingSteps to design and implement a GUI continued:
5. Include the event handler class – -for each button, add an object of a listener class -the listener classes must implement the ActionListener interface -Place commands for the action in the actionPerformed method
class AddInterestListener implements ActionListener { public void actionPerformed (ActionEvent event){ //appropriate button action is placed here } }
Y. Daniel Liang 80
Event-Driven Programming
Steps to design and implement a GUI continued:
6. Include listener objects and attach them to the event sources
ActionListener listener = new AddInterestListener(); button.addActionListener(listener);
7. Choose a layout manager
Y. Daniel Liang 81
Event-Driven Programming Programs with GUIs must respond to events,
generated by GUI components, that indicate that specific actions have occurred
A special category of classes, called listeners, wait for events to occur
Therefore, a GUI program is composed of:– the code that presents the GUI to the user– the listeners that wait for events to occur– the specific code that is executed when events occur
Y. Daniel Liang 82
Event-Driven Programming
There is a listener interface defined for each event type
Each listener interface contains the abstract methods required to respond to specific events
A listener class implements a particular listener interface
Listeners are "added" to a particular GUI component
When a component generates an event, the method corresponding to that event is executed in the listener
Y. Daniel Liang 83
Handling Events
Run TestActionEvent
Y. Daniel Liang 84
Event Interfaces Multiple listeners can be added to a component Multiple components can be processed by the
same listener Furthermore, one listener class can implement
multiple listener interfaces Therefore one class can listen for many types of
events
Run program TestMultipleListner
Y. Daniel Liang 85
The GUI Program Model
Listeners
Program-specific
GUIEvent effects
Add listeners Handle events
Y. Daniel Liang 86
Useraction
Source Object
Register a listener object
Trigger an event
Event Object
GenerateAn event
Listener Object
Event Handler
Notify Listener
Event Registration, Listening, and Handling
An event is triggered by the user actions on the source object The source object generates the event object and invokes the handle of the listener object to process the event
Y. Daniel Liang 87
JButton
A button is a component that triggers an action event when clicked. The following are JButton non-default constructors:
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)
Y. Daniel Liang 88
Responding to JButton Eventspublic void actionPerformed(ActionEvent e) { // Get the button label String actionCommand = e.getActionCommand();
// Make sure the event source is a button if (e.getSource() instanceof JButton) // Make sure it is the right button if ("My Button".equals(actionCommand) System.out.println ("Button pressed!");}
Y. Daniel Liang 89
JButton
RunRunButtonDemoButtonDemo
Run ButtonDemo.java
Y. Daniel Liang 90
JLabel
A label is a display area for a short text, an image, or both. A label defines a line of text displayed on a GUILabels are static in the sense that they cannot be selected or modified by the human user once added to a containerA label is instantiated from the Label classThe Label class contains several constructors and methods for setting up and modifying a label's content and alignment
Y. Daniel Liang 91
JText Field
Most graphical programs collect text input through text fields. A text field displays a single line of text in a GUI
Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).
Y. Daniel Liang 92
JTextField
The text field is defined by the JTextField class. When you construct the text field, you need to supply the width – the estimated number of characters entered by the user.
final int FIELD_WIDTH = 12; //constant final JTextField rateField = new JTextField(FIELD_WIDTH);
You need to label each text field:
JLabel rateLabel = new JLabel(“Interest Rate: “);
Run InvestViewer.java (BankAccount.java)
Y. Daniel Liang 93
JTextField Methods
getText()Returns the string from the text field.
setText(String text)Puts the given string in the text field.
setEditable(boolean editable)Enables or disables the text field to be edited. By default, editable is true.
setColumns(int)Sets the number of columns in this text field.The length of the text field is changeable.
Y. Daniel Liang 94
JTextArea
A text area is similar to a TextField, but permits the user to enter multiple lines of text
It is defined by the JTextArea classes
A text area automatically has scrollbars on its bottom and right sides
Run ViewFile.java
Y. Daniel Liang 95
JTextArea
If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.
Y. Daniel Liang 96
JComboBox
A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value. To create a choice, use its default constructor:
JComboBox()
Y. Daniel Liang 97
JComboBox Methods
To add an item to a JComboBox jcbo, use
jcbo.addItem(Object item)
To get an item from JComboBox jcbo, use
jcbo.getItem()
Y. Daniel Liang 98
JCheckBox
A check box is a component that enables the user to toggle a choice on or off, like a light switch.
Y. Daniel Liang 99
JRadioButton
Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.
Y. Daniel Liang 100
JRadioButton Properties
JRadioButton has all the properties in JButton. Additionally, JButton has the following property:
selected
Y. Daniel Liang 101
Grouping Radio Buttons
ButtonGroup btg = new ButtonGroup();
btg.add(jrb1);
btg.add(jrb2);
Y. Daniel Liang 102
Example 11.8: Using Radio ButtonsThis example shows a program that simulates traffic lights. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time. No light is on when the program starts.
RunRunRadioButtonDemoRadioButtonDemo
Y. Daniel Liang 103
JOptionPane Dialogs
A dialog is normally used as a temporary window to receive additional information from the user, or to provide notification that some event has occurred.
Y. Daniel Liang 104
Message Dialogs
A message dialog box simply displays a message to alert the user and waits for the user to click the OK button to close the dialog.
icon message
button
Y. Daniel Liang 105
Message Types (5)The messageType is one of the following constants:
JOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGE
Y. Daniel Liang 106
Message Types, cont.
Y. Daniel Liang 107
Confirmation Dialogs
A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The message dialog does not return any value. A confirmation dialog asks a question and requires the user to respond with an appropriate button. The confirmation dialog returns a value that corresponds to a selected button.
Y. Daniel Liang 108
Input DialogsAn input dialog box is used to receive input from the user. The input can be entered from a text field or selected from a combo box or a list. Selectable values can be specified in an array, and a particular value can be designated as the initial selected value.
Y. Daniel Liang 109
Option Dialogs
An option dialog allows you to create custom buttons.
Y. Daniel Liang 110
Example: Creating Standard Dialogs
Objective: This example demonstrates using standard dialogs. The program prompts the user to select the annual interest rate from a list in an input dialog, the number of years from a combo box in an input dialog, and the loan amount from an input dialog, and displays the loan payment schedule in a text area inside a JScrollPane in a messasge dialog.
Y. Daniel Liang 111
Example: Creating Standard Dialogs, cont.
RunRun
JOptionPaneDemo(Mortgage.java)
JOptionPaneDemo(Mortgage.java)
Y. Daniel Liang 112
Menus make selections easier
are widely used in windows applications
Y. Daniel Liang 113
Menus
JComponent
JMenuBar AbstractButton JPopupMenu
JMenuItem
JRadioButtonMenuItem JMenu JCheckBoxMenuItem
Y. Daniel Liang 114
Menus
Java provides several classes—to implement menus in a frame JMenuBar – the top-level container used to hold menus
JMenu the menu bar itself -It may hold submenus
JMenuItem has no further submenus The user can select (or toggle on or off) to make a selection
Y. Daniel Liang 115
Menus JMenuItem Contd. The menu item can be an instance of:
JMenuItem JCheckBoxMenuItem JRadioButtonMenuItem
When the user selects a menu item, the menu item sends an action event. Therefore, you should add a listener to each menu item.
jmenuItemExit.addListener(listener);
Y. Daniel Liang 116
Menus Classes contd. JCheckBoxMenuItem permits you to check or uncheck a menu item same as a checkbox
JRadioButtonMenuItem permits you to choose between mutually exclusive menus
A JFrame or JApplet can hold a menu bar to which the pull-down menus are attached. Menus consist of menu items that the user can select (or toggle on or off). Menu bars can be viewed as a structure to support menus.
Y. Daniel Liang 117
CreateMenus
Y. Daniel Liang 118
CreateMenus
Y. Daniel Liang 119
Create Menus
Y. Daniel Liang 120
Create Menu Submenu
Y. Daniel Liang 121
Menus
Run Program: CreateMenus Need Inputs: new.gif and open.gif
Y. Daniel Liang 122
Run Gui.java
Swap text
Clear Screen
Enter text
Y. Daniel Liang 123
The JMenuBar Class
JFrame f = new JFrame();f.setSize(300, 200);f.setVisible(true);JMenuBar mb = new JMenuBar(); f.setJMenuBar(mb);
A menu bar holds menus; the menu bar can only be added to a frame. Following is the code to create and add a JMenuBar to a frame:
Y. Daniel Liang 124
The Menu Class
JMenu fileMenu = new JMenu("File", false);JMenu helpMenu = new JMenu("Help", true);mb.add(fileMenu);mb.add(helpMenu);
You attach menus onto a JMenuBar. The following code creates two menus, File and Help, and adds them to the JMenuBar mb:
Y. Daniel Liang 125
The JMenuItem Class
fileMenu.add(new JMenuItem("new"));fileMenu.add(new JMenuItem("open"));fileMenu.add(new JMenuItem("-"));fileMenu.add(new JMenuItem("print"));fileMenu.add(new JMenuItem("exit"));fileMenu.add(new JMenuItem("-"));
You add menu items on a menu. The following code adds menu items and item separators inmenu fileMenu:
Y. Daniel Liang 126
Submenus
JMenu softwareHelpSubMenu = new JMenu("Software");
JMenu hardwareHelpSubMenu = new JMenu("Hardware");
helpMenu.add(softwareHelpSubMenu);
helpMenu.add(hardwareHelpSubMenu);
softwareHelpSubMenu.add(new JMenuItem("Unix"));
softwareHelpSubMenu.add(new JMenuItem("NT"));
softwareHelpSubMenu.add(new JMenuItem(“Vista"));
You can add submenus into menu items. The following code adds the submenus “Unix,” “NT,” and “Vista” into the menu item “Software.”
Y. Daniel Liang 127
JScrollBar
A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.
Y. Daniel Liang 128
Example 11.13: Using Scrollbars
This example uses horizontal and vertical scrollbars to control a message displayed on a panel. The horizontal scrollbar is used to move the message to the left or the right, and the vertical scrollbar to move it up and down.
ScrollBarDemo(MessagePanel)ScrollBarDemo(MessagePanel) RunRun
Y. Daniel Liang 129
JScrollPane
A scroll pane is a component that supports automatically scrolling without coding.