View
226
Download
0
Tags:
Embed Size (px)
Citation preview
FIT1002 2006
1
FIT1002FIT1002Computer ProgrammingComputer Programming
Unit 21-22Unit 21-22
Basic GUI ProgrammingBasic GUI Programming
FIT1002 2006
2
ObjectivesObjectives
By the end of this lecture, students should:
• understand event-driven programming• understand the basic structure of a Swing program
• understand container-hierarchies in GUIs • know the most fundamental Swing classes
• be able to implement a simple GUI in Swing(single-threaded)
FIT1002 2006
3
Cross-Platform ProgrammingCross-Platform Programming
Java Design Goals
• platform independence• web-based programs
the GUI must be independent of the platformthe GUI “toolkit” is an integral part of Java
• this is (almost) a novelty in Java: Smalltalk had the same property, but Java is the first mainstream language that has GUI capabilities built in.
FIT1002 2006
4
A Swing GUI ExampleA Swing GUI Example
Java GUIs are built from
pre-defined GUI objects:
• Windows, • Buttons, • TextFields,
• Menus• etc.
FIT1002 2006
5
Event-Driven ProgrammingEvent-Driven Programming
GUI programs are usually event-driven
• the flow of control is not directed by a single algorithm
• Instead actions are triggered by events (e.g. a button click)
• In response to an event a pre-defined action is triggered
• An event if “fired” by a particular object (e.g. a button)
• The event is then sent to the reacting object which handles it
• The reacting object is called a “Listener”
• It must be registered as a listener with the object that fires the events in order to “receive” events from it.
component listenerevent
FIT1002 2006
6
Container HierarchiesContainer Hierarchies
GUIs are usually organized in a hierarchical fashion with containers inside other containers.
Example: The top-level window contains a menu-bar which in turn contains menu elements
– Containera component that can hold other components
– ComponentGUI element that can fire events
– Panelstandard container used for grouping objects
– Framea window with a title and menus
FIT1002 2006
7
Every component must be ina container to be displayedunless it is a top-level object (JFrame)
Each top-level container has a content pane
A Frame ExampleA Frame Example
Frame
ContentPane
Menu Bar
Label
FIT1002 2006
8
Containment HierarchyContainment Hierarchy
The containment hierarchy for the example of the previous slide:
JFrame
content pane menu bar
JLabel
...
FIT1002 2006
9
Swing Class Swing Class HierarchyHierarchy
object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
javax.swing.JComponent
javax.swing.JPanel
…
…
javax.swing.JLabel
javax.swing.JTextComponent
…
FIT1002 2006
10
Swing Class HierarchySwing Class Hierarchy
FIT1002 2006
11
Swing Class HierarchySwing Class Hierarchy
FIT1002 2006
12
Swing Container ClassSwing Container Class
Every program using the Swing GUI must have at least one top-level Swing container class.
Commonly used top-level Swing container classes are:
JFrame: implements a single main window
JDialog: implements a window for a “temporary” dialog
(e.g. a short “Quit without save?” confirmation)
JApplet: implements an applet within a browser window
Need to import the Swing package:
import javax.Swing.*;
FIT1002 2006
13
Common Swing ComponentsCommon Swing Components
JButtonJCheckBoxJRadioButtonJListJMenuJTextFieldetc.
FIT1002 2006
14
JFrameJFrame
As your top-level window you need a JFrame
You add components to a JFrame using the add command
add(myLabel);
You need to make the JFrame visible explicitly
setVisible(true);
FIT1002 2006
15
JLabelJLabel
A JLabel is a component used to display some text.
It is passive, for displaying only: it cannot be used for input.
The text in a JLabel can be set in the constructor
Jlabel myLabel=new Jlabel(“Hello”);
and can be changed with a method call
myLabel.setText(“new Text”);
The JLabel must be added to some visible container to appear
JFrame myFrame = new Jframe();
myFrame.add(myLabel);
FIT1002 2006
16
Example: Hello WorldExample: Hello World
import java.awt.*;import javax.swing.*;
public class Hello0 extends JFrame{public Hello0() {
JLabel l = new JLabel("Hello World!"); add(l); setVisible(true);
}}
FIT1002 2006
17
Example: Hello World (Complete)Example: Hello World (Complete)import java.awt.*;import javax.swing.*;
public class Hello1 extends Jframe {public Hello1() { setTitle("Hello World");
setSize(100, 75); setLocation(200,200); setDefaultCloseOperation(EXIT_ON_CLOSE); Container contentPane = getContentPane();
JLabel l = new JLabel("Hello World!"); contentPane.add(l); setVisible(true);
}}
FIT1002 2006
18
Notes on “Hello World”Notes on “Hello World”A JFrame object is a basic window that may include a border,
title, menu bar as well as buttons for minimizing the window, changing the size of the window and closing the window, etc.
• You can subclass JFrame to define a new kind of window object
• The size of the window is set with setSize(width, height)• The initial window position is set with setLocation(x, y)• Units are measured using pixels. • Normally should not add a component to the JFrame directly
• Instead you add to its “content pane” • This is a default container for the visible area of the frame.
• You get access to the content pane usingContainer contentPane = getContentPane();
FIT1002 2006
19
Exiting from a GUI programExiting from a GUI program
To exit from a GUI program you need to use
System.exit(0)
If you do not perform an explicit exit, the program will keep running.
You can initialize a JFrame so that it automatically performs an exit when the “close button” is clicked.
setDefaultCloseOperation(EXIT_ON_CLOSE);
FIT1002 2006
20
Layout ManagersLayout Managers
• If a container has more than a single object in it the arrangement (layout) of the objects needs to be defined.
• This is (usually) not defined in absolute terms, because the windows are (usually) resizable.
• Instead relative positions are defined.
• The exact layout is then calculated by a “Layout Manager”.
• There are several different pre-defined Layout Manager classes:• FlowLayout• BorderLayout, etc…
FIT1002 2006
21
Flow Layout ManagersFlow Layout Managers
The FlowLayout manager is the simplest layout managerIt arranges components one after the other, going
from left to rightComponents are fitted in the order in which they are
added.
To use flow layout1. create a flow layout manager 2. set it as the layout manager for the container
user resizes window
FlowLayout changes
FIT1002 2006
22
Flow Layout ExampleFlow Layout Example
public class Hello1x2flow extends Jframe {public Hello1x2flow() { …
Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); JLabel l1 = new JLabel("Hello World!");
contentPane.add(l1); JLabel l2 = new JLabel("How are you?"); contentPane.add(l2); setVisible(true);
}}
FIT1002 2006
23
The BorderLayout manager is somewhat more flexible.It allows the programmer to arrange the components in five regions.
To use border layout• create a border layout manager • set it as the layout manager for the container• define the region for each component in the call to add
To achieve complex layout you can nest containers with different layout managers.
BorderLayoutBorderLayout
FIT1002 2006
24
Border Layout ExampleBorder Layout Example
public class Hello1x2flow extends Jframe {public Hello1x2flow() { …
Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout());
JLabel l1 = new JLabel("Hello World!"); contentPane.add(l1, BorderLayout.NORTH); JLabel l2 = new JLabel("How are you?"); contentPane.add(l2, BorderLayout.SOUTH); setVisible(true);
}}
FIT1002 2006
25
Pop-up DialogsPop-up Dialogs
Pop-up Dialogs are used for short-lived windows, for example a quick “yes-no” confirmation.
To generate a dialog you need to 1. create a JOptionPane2. call a dialog method for the appropriate type of dialog
FIT1002 2006
26
Notes on Pop-up DialogsNotes on Pop-up Dialogs
All pop-up Dialogs are modal, i.e. they block other windows while they are displayed.
The first parameter of the show dialog methods is the parent frame you can set this to null if you do not want the dialog to depend on another window.
JOptionPane p = new JOptionPane();String answer = p.showInputDialog(null, "Who are you?");
FIT1002 2006
27
ButtonsButtons
• A button is any item that can be “pressed” or “clicked”.
• Before you can add a button to a container, you will need to create a button component of class JButton:
JButton newButton = new JButton(“Hello”);
• The argument to the constructor is the string that will appear on the button when it is displayed.
• You add the button to a container using the add method:
add(newButton);
FIT1002 2006
28
Hello with ButtonHello with Button
… Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout());
JLabel l = new JLabel("Hello World!"); l.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(l, BorderLayout.NORTH); JButton b = new JButton("Hello!"); contentPane.add(b, BorderLayout.CENTER); …
FIT1002 2006
29
Button Events and ListenersButton Events and Listeners
How do we make a button react?When a button is clicked it fires an event.
To program the function of the button you need to define a reaction to this event. For this you need a “Listener” object that processes this even.
To program a response to a button being clicked you need to:
1.Define an appropriate listener class which conforms to a standard listener interface definition (ActionListener). In particular, it must have an actionPerformed method. This will be executed when an event is received.
2.Create a listener object,3.Register this listener object so that it can react
(“listen”) to ActionEvents fired by this button.
FIT1002 2006
30
Listener ExampleListener Example
Here is a simple listener that just displays a pop-up box with a message. The actionPerformed method will be called as the reaction to a button event.
import java.awt.*;import java.awt.event.*;import javax.swing.*;
public class ConfirmActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { JOptionPane p = new JOptionPane(); p.showMessageDialog(null,
"You pressed the button!");}
}
FIT1002 2006
31
Interfaces (revision) Interfaces (revision)
implements ActionListener in the class header indicates that the class ConfirmActionListener implements a so-called “interface” with the name ActionListener.
An interface is a defined list of method signatures that a class which implements it must offer. Implementing an interface is like inheriting a number of method headers without the actual code.
The implementing class must give concrete methods implementations for these (much as if it would override an inherited method).
( here: public void actionPerformed(ActionEvent e) ).
Details: Savitch, Chapter 13
FIT1002 2006
32
Registering a Listener Registering a Listener to let the listener receive events, you need to register it for a button.
public class Hello3 extends Jframe { public Hello3() { … JLabel l = new JLabel("Hello World!"); l.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(l, BorderLayout.NORTH); JButton b = new JButton("Hello!"); ConfirmActionListener listener = new ConfirmActionListener(); b.addActionListener( listener ); contentPane.add(b, BorderLayout.CENTER); setVisible(true); }}
FIT1002 2006
33
Exchanging Data With a Listener Exchanging Data With a Listener
The listener method receives only the event as a parameterpublic void actionPerformed(ActionEvent e)
How to give the listener access to other data in the program?
An elegant way is to store it in an instance variable of the listener, which can be set when the listener object is constructed…
Can you think of other ways?
Example: a button listener for Hello World Example that – asks for the users name (using a pop-up dialog) – sets the text in the JLabel to greet the user by name
FIT1002 2006
34
Hello World with FeedbackHello World with Feedback
button press,event handler called
event handler changes JLabel
empty JLabel
FIT1002 2006
35
Hello World with Feedback (I)Hello World with Feedback (I)
public class LabelFillListener implements ActionListener {
public JLabel myLabel; public LabelFillListener(JLabel j) { myLabel = j; } public void actionPerformed(ActionEvent e) { JOptionPane p = new JOptionPane(); String answer = p.showInputDialog(null, "Who are you?"); myLabel.setText("Hello "+answer+"!");}
}
FIT1002 2006
36
Hello World with Feedback (II)Hello World with Feedback (II)public class Hello4 extends Jframe {public Hello4() { …
JLabel l = new JLabel(" "); l.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(l, BorderLayout.NORTH); JPanel south = new JPanel(); south.setLayout(new FlowLayout()); contentPane.add(south, BorderLayout.CENTER); JButton b = new JButton("Hello!"); b.addActionListener(new LabelFillListener(l)); b.setSize(100,20); south.add(b); … }}
FIT1002 2006
37
Event-handlers are blockingEvent-handlers are blocking
• Event handlers (listener’s action performed method) block the program while they execute.
•You must ensure that your event handler terminates.
• Termination of the handler returns control to the GUI.
FIT1002 2006
38
The Event ObjectThe Event Object
The listener method receives the event as a parameterpublic void actionPerformed(ActionEvent e)
The event is an object of class ActionEvent.It contains useful information
– the object that fired the event– the text on the button (if a button fired the event)– the time of the event– etc.
You can, for example, use this information to distinguish which button was clicked if you attach the same listener to several buttons.
You can retrieve this information with methods defined in the ActionEvent class. For details see the Java API description.
FIT1002 2006
39
GUI Example for “Secret Message”GUI Example for “Secret Message”
The picture below shows a GUI for “Secret Message” (Tutorial 8).The code for this GUI will be discussed in detail in the tutorial.
It contains JLabels and JButtons and two new Swing component:• JTextField• JRadioButton JFrame
JTextFieldJLabel JRadioButton JButton
FIT1002 2006
40
JTextFieldJTextField
A JTextField is an input field for text.
Its contents can be read with the methodpublic String getText()
Its contents can be set with the method public void setText(Strings s)
FIT1002 2006
41
Extending GUI ComponentsExtending GUI Components
Define your own custom GUI components if you need more complex elements.
For example, we may often want a text field with a label.
We can define this based on JTextField and JLabel.Both components are “wrapped” into a shared JPanel.
LabeledTextField
FIT1002 2006
42
Example: LabeledTextField (I)Example: LabeledTextField (I)
import java.awt.*;import java.awt.event.*;import javax.swing.*;
public class LabeledTextField extends JPanel {
public JTextField myTextField; public LabeledTextField(String s1) { this.setLayout(new FlowLayout()); this.add(new JLabel(s1)); myTextField = new JTextField(); myTextField.setColumns(20); this.add(myTextField); } …
FIT1002 2006
43
Example: LabeledTextField (II)Example: LabeledTextField (II)
… // continuation of class LabeledTextField
public void clear() { myTextField.setText(""); } public void setText(String s) { myTextField.setText(s); }
public String getText() { return myTextField.getText(); }}
FIT1002 2006
44
JRadioButtonJRadioButton
A JRadioButton is an element in a group of buttons in which only one button can be activated at a time.
All JRadioButtons in a group belong to one ButtonGroup.When a JRadioButton is activated all other buttons in the same are
deactivated.The state of a JRadioButton can be read with the methodpublic boolean isSelected()The state of a JRadioButton can be set with the method public void setSelected(boolean b)
Button Group
JRadioButton
FIT1002 2006
45
Example: JRadioButtonExample: JRadioButton
public class RadioChoice extends JPanel { JRadioButton b1; JRadioButton b2; public RadioChoice(String s1, String s2) {
this.setLayout(new BorderLayout()); ButtonGroup group = new ButtonGroup(); b1 = new JRadioButton(s1); b1.setSelected(true); b2 = new JRadioButton(s2); this.add(b1, BorderLayout.NORTH); this.add(b2, BorderLayout.SOUTH); group.add(b1); group.add(b2);
} public boolean simple() {
return b1.isSelected(); }}
FIT1002 2006
46
JListJList
JLists allow us to display a list of items (Strings) from which the user can select.
They are commonly be wrapped into a JScrollPane.A JScrollPane is simply a panel that allows to scroll its contents.
FIT1002 2006
47
JListJList
public class ListExample extends JFrame {public ListExample(String[] words) { …
Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JList picklist = new JList(words); picklist.setFixedCellWidth(100); picklist.addListSelectionListener( new ListListener()); JScrollPane scroller = new JScrollPane(picklist); contentPane.add(scroller, BorderLayout.CENTER);}
}
Note how the contents of the list is set in the constructor
FIT1002 2006
48
ListSelectionListenerListSelectionListener
public class ListListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) { String s = (String)
((JList)(e.getSource())).getSelectedValue(); (new JOptionPane()).showMessageDialog(
null, "You have selected "+s);}
}
You can read the currently selected value using the method
public String getSelectedValue()
You can also program listeners that react to selection changes.
These must implement the ListSelectionListener interface.
FIT1002 2006
49
ReadingReading
• Savitch•Chapter 17•Section 17.3 restricted to Flow Layout and Border Layout
FIT1002 2006
50
Menus Menus (advanced, optional)(advanced, optional)
It is straight forward to add a menu to a JFrame.A menu is constructed hierarchically from the following items
menubar (JMenuBar) menus (JMenu, the components in a menubar)
menu items (JMenuItem, the components of an individual menu)
Listeners are attached to the menu items.
JMenuBar
JMenuJMenuItems are currentlyinvisible asno menu ispulled down.
FIT1002 2006
51
Menus Menus (advanced, optional)(advanced, optional)
public class CryptoApp extends Jframe {public CryptoApp() { …
south.add(actionButtons); constructMenu(a1, a2, modeButtons); // we want some menu items to perfrom the same // action as the two buttons // so we will re-use their listeners // we also need the RadioButtons, as the menu items // will operate on these setVisible(true); }
As the menu construction is fairly length, we wrap it into a separate method
FIT1002 2006
52
Menus Menus (advanced, optional)(advanced, optional)
public void constructMenu(ActionListener encoderListener, ActionListener decoderListener, RadioChoice modeButtons) {
JMenu actionMenu = new JMenu("Action"); JMenuItem encodeItem = new JMenuItem("Encode"); encodeItem.addActionListener(encoderListener); actionMenu.add(encodeItem); JMenuItem decodeItem = new JMenuItem("Decode"); decodeItem.addActionListener(decoderListener); actionMenu.add(decodeItem); …
here we construct the first menu (“Action”).
Note how we simply attach the same ActionListener that we used for the buttonsto the menu items. The result is that they will perform exactly the same action!
FIT1002 2006
53
Menus Menus (advanced, optional)(advanced, optional)
… JMenu modeMenu = new JMenu("Mode");
ModeMenuListener modeListener = new ModeMenuListener(modeButtons); JMenuItem simpleItem = new JMenuItem("Simple"); simpleItem.addActionListener(modeListener); modeMenu.add(simpleItem); JMenuItem betterItem = new JMenuItem("Better"); betterItem.addActionListener(modeListener); modeMenu.add(betterItem);
here we construct the second menu (“Mode”).Note that we use a different listener type. We attach the same listener object to both menu items.
FIT1002 2006
54
Menus Menus (advanced, optional)(advanced, optional)
… JMenuBar myMenuBar = new JMenuBar(); myMenuBar.add(actionMenu); myMenuBar.add(modeMenu); this.setJMenuBar(myMenuBar);
} // end of constructMenu() method
finally we construct and install the whole menu bar into the frame.
FIT1002 2006
55
Menu Listeners Menu Listeners (advanced, optional)(advanced, optional)
public class ModeMenuListener implements ActionListener {
private RadioChoice choiceButtons;
public ModeMenuListener(RadioChoice modeButtons) { choiceButtons=modeButtons; }
public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Simple")) choiceButtons.setSimple(); if (cmd.equals("Better")) choiceButtons.setBetter();}
}
Listeners for menu selection events are also ActionListeners.The getActionCommand() method for the ActionEvent yields the text of the selected menu item that fired the event. The listener can use this to determinewhat action should be triggered.