Lesson Xii. Gui and Event Programming (1/2) : Vu Thi Huong Giang
Lesson Xii. Gui and Event Programming (1/2) : Vu Thi Huong Giang
Lesson Xii. Gui and Event Programming (1/2) : Vu Thi Huong Giang
1
Objectives
2
Content
I. Introduction
II. Programming GUI with AWT
III. AWT Event-Handling
3
I. Introduction
4
1. Introduction
Title bar
Menus Menu bar
Combo box
Button
Scroll bar
5
Java APIs for graphics programming
6
Content
I. Introduction
II. Programming GUI with AWT
III. AWT Event-Handling
7
II. Programming GUI with
AWT
8
2.1. AWT Packages
• Huge: there are 12 packages.
– Only 2 packages: java.awt & java.awt.event are commonly-used
– Platform-independent & device-independent
• Core graphics classes of java.awt:
– GUI Component classes (such as Button, TextField, and Label),
– GUI Container classes (such as Frame, Panel, Dialog and
ScrollPane),
– Layout managers (such as FlowLayout, BorderLayout and
GridLayout),
– Custom graphics classes (such as Graphics, Color and Font).
• java.awt.event package supports event handling
– Event classes (such as ActionEvent, MouseEvent, KeyEvent and
WindowEvent),
– Event Listener Interfaces (such as ActionListener, MouseListener,
KeyListener and WindowListener),
– Event Listener Adapter classes (such as MouseAdapter,
KeyAdapter, and WindowAdapter).
9
2.2. Containers and Components
10
2.3. AWT Container Classes
• Top-level AWT containers: Frame, Dialog
and Applet.
• Frame:
– provides "main window" for GUI application, including:
• a title bar (containing an icon, a title, the minimize,
maximize/restore-down and close buttons)
• an optional menu bar
• the content display area.
• Dialog: a "pop-up window“, including:
– a title-bar (containing an icon, a title and a close button)
– a content display area
• Applet: top-level container for an applet - a Java
program running inside a browser
11
2.3. AWT Container Classes
12
2.3. AWT Container Classes
13
2.4. AWT Component Classes
14
2.4. AWT Component Classes
• java.awt.Label: provides a text description message.
• Constructors:
– // Construct a Label with the given text String, of the text alignment
– public Label(String strLabel, int alignment);
– public Label(String strLabel); // Construct a Label with the given text
– public Label(); // Construct an initially empty Label
• Constants:
– public static final LEFT; // Label.LEFT
– public static final RIGHT; // Label.RIGHT
– public static final CENTER; // Label.CENTER
• Public methods:
– public String getText();
– public void setText(String strLabel);
– public int getAlignment();
– public void setAlignment(int alignment);
15
2.4. AWT Component Classes
• To construct a Component and add into a
Container:
– Declare the component with an identifier
– Construct the component
– Identify the container designed to hold this component.
Use add method:
• Ex: aContainer.add(aComponent)
• Example:
Label lblInput;
lblInput = new Label("Enter ID");
this.add(lblInput);
lblInput.setText("Enter password");
lblInput.getText();
16
2.4. AWT Component Classes
• java.awt.Button: triggers a certain programmed action
upon clicking.
• Constructors:
– public Button(String buttonLabel);
– public Button(String buttonLabel);
• Public Methods
– public String getLabel();
– public void setLabel(String buttonLabel);
– public void setEnable(boolean enable);
• Example:
– Button btnColor = new Button("Red");
– this.add(btnColor);
– ...
– btnColor.setLabel("green");
– btnColor.getLabel();
17
2.4. AWT Component Classes
18
2.5. Layout Managers
19
Set a layout manager
• A container has a setLayout() method to set its layout
manager:
– public void setLayout(LayoutManager mgr)
• To set up the layout of a Container:
– Construct an instance of the chosen layout object, e.g., new
FlowLayout()
– Invoke the setLayout() method, with the layout object created as
the argument;
– Place the GUI components into the Container using the add()
method in the correct order; or into the correct zones.
• Example:
Panel p = new Panel();
p.setLayout(new FlowLayout());
p.add(new JLabel("One"));
p.add(new JLabel("Two"));
p.add(new JLabel("Three"));
20
Layout managers
21
a. FlowLayout
• Inside a Container with FlowLayout:
– components are arranged from left-to-right (in the added
order)
– when one row is filled, new row will be started
• Constructors:
– public FlowLayout();
– public FlowLayout(int align);
– public FlowLayout(int align, int hgap, int vgap);
• Align:
– FlowLayout.LEFT (or LEADING)
– FlowLayout.RIGHT (or TRAILING)
– FlowLayout.CENTER
• hgap, vgap: horizontal/vertical gap between the
components.
• By default: hgap=5, vgap=5, align=CENTER
22
FlowLayout example
import java.awt.*;
import java.awt.event.*;
public class AWTFlowLayout extends Frame {
public AWTFlowLayout () {
setLayout(new FlowLayout());
add(new Button("Button 1"));
add(new Button("This is Button 2"));
add(new Button("3"));
add(new Button("Another Button 4"));
add(new Button("Button 5"));
add(new Button("One More Button 6"));
24
c. BorderLayout
• With BorderLayout, container is divided into 5 zones: EAST,
WEST, SOUTH, NORTH, and CENTER
• To add a components:
– aContainer.add(acomponent, aZone)
• aZone: can be
– BorderLayout.NORTH (or PAGE_START)
– BorderLayout.SOUTH (or PAGE_END)
– BorderLayout.WEST (or LINE_START)
– BorderLayout.EAST (or LINE_END)
– BorderLayout.CENTER
– aContainer.add(aComponent): adds the component to the CENTER
• No need to add components to all the 5 zones
• Constructors:
– public BorderLayout();
– public BorderLayout(int hgap, int vgap);
– By default hgap=0, vgap=0
25
Content
I. Introduction
II. Programming GUI with AWT
III. AWT Event-Handling
26
III. AWT Event-Handling
3.1. Introduction
3.2. Event-Handling Steps
3.3. Available pairs of Event and Listener
3.4. Adapters
27
3.1. Introduction
• Event-handling model: “Event-driven”
– When event has been fired (by user input): a piece of
event-handling codes is executed
• Package java.awt.event: contains AWT's event-
handling classes
• 3 objects involved in the event-handling: source,
listenser, event
– source object interacts with the user to create an event
object
– event object will be messaged to all the registered
listener objects
– appropriate event-handler method of the listener(s) is
called-back to provide the response
28
3.1. Introduction
29
3.2. Event-Handling Steps
30
a. Source object registers for a certain
type of event
• The source & listener understand each other via
an agreed-upon interface
• 3 steps: (to support XxxEvent event type for a
Source)
– Declare an interface called XxxListener, container the
names of the handler methods
– Listeners interested in the XxxEvent must implement the
XxxListener interface
– Source has to maintain the list of listener object(s).
• public void addXxxListener(XxxListener l);
• public void removeXxxListener(XxxListener l);
31
b. Example to handle MouseEvent
• Step 1: Declare MouseListener interface (by awt)
interface MouseListener {
// Called back upon mouse-button pressed
public void mousePressed(MouseEvent evt);
// Called back upon mouse-button released
public void mouseReleased(MouseEvent evt);
// Called back upon mouse-button clicked (pressed and released)
public void mouseClicked(MouseEvent evt);
// Called back when mouse pointer entered the component
public void mouseEntered(MouseEvent evt);
// Called back when mouse pointer exited the component
public void mouseExited(MouseEvent evt);
}
32
b. Example to handle MouseEvent
• Step 2: Create a Listener class implement MouseListener interface
33
b. Example to handle MouseEvent
• Step 3: Create a Listener class implement MouseListener
interface
import java.awt.*;
public class ButtonEventExample extends Frame {
public ButtonEventExample () {
setLayout(new FlowLayout());
Button b = new Button("Button");
add(b);
b.addMouseListener(new MyMouseListener());
35
a. ActionEvent and ActionListener
Interface
• To fire an ActionEvent
– Click a Button
– Pushing the "enter" key on a TextField
• The ActionEvent will be sent to all listeners
– Listener for ActionEvent must implement ActionListener
interface.
interface ActionListener {
// Called back upon button clicked, enter key pressed
public void actionPerformed(ActionEvent e);
}
36
a. ActionEvent and ActionListener
Interface-Example
public class AWTCounter extends Frame implements ActionListener {
public int count = 0;
private TextField txt;
public AWTCounter(){
setLayout(new FlowLayout());
Button b = new Button("Button");
add(b);
b.addActionListener(this);
txt = new TextField();
add(txt);
setTitle("ActionEvent example");
setSize(280, 150);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt) {
count++;
txt.setText(count + "");
}
public static void main(String args[]){
new AWTCounter();
}
} 37
b. WindowEvent and WindowListener
Interface
• A WindowEvent is fired when a window (e.g.,
Frame) has been:
– opened/closed
– activated/deactivated
– iconified/deiconified
via the 3 buttons at the top-right corner or other
means.
• The source of a WindowEvent shall be a top-
level window-container such as Frame.
38
b. WindowEvent and WindowListener
Interface
• A WindowEvent listener must implement WindowListener interface.
/* Called-back when the user attempts to close the window by clicking the window
close button. This is the most-frequently used handler*/
public void windowClosing(WindowEvent e).
/* Called-back the first time a window is made visible. */
public void windowOpened(WindowEvent e)
/* Called-back when a window has been closed as the result of calling dispose on
the window.*/
public void windowClosed(WindowEvent e)
/* Called-back when the Window is set to be the active Window.*/
public void windowActivated(WindowEvent e)
/* Called-back when a Window is no longer the active Window*/
public void windowDeactivated(WindowEvent e)
/* Called-back when a window is changed from a normal to a minimized state.*/
public void windowIconified(WindowEvent e)
/* Called-back when a window is changed from a minimized to a normal state*/
public void windowDeiconified(WindowEvent e).
39
c. MouseEvent and MouseListener
Interface
• A MouseEvent is fired when you
– press, release, or click (press followed by release) a
mouse-button (left or right button) at the source object;
– or position the mouse-pointer at (enter) and away (exit)
from the source object.
• A MouseEvent listener must implement the
MouseListener interface
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
• Example already presented
40
d. MouseEvent and
MouseMotionListener Interface
• A MouseEvent is also fired when we moved and
dragged the mouse pointer at the source object.
– But we need to use MouseMotionListener to handle the
mouse-move and mouse-drag.
• The MouseMotionListener interface:
interface MouseMotionListener{
/* Called-back when a mouse-button is pressed on the
source component and then dragged.*/
public void mouseDragged(MouseEvent e)
/* Called-back when the mouse-pointer has been moved onto
the source component but no buttons have been pushed.*/
public void mouseMoved(MouseEvent e)
}
41
public MouseMotionDemo() {
setLayout(new FlowLayout());
interface KeyListener{
/* Called-back when a key has been typed (pressed and
released)*/
public void keyTyped(KeyEvent e)
/* Called-back when a key has been pressed*/
public void keyPressed(KeyEvent e)
/* Called-back when a key has been released*/
public void keyReleased(KeyEvent e)
}
43
Example of handling KeyEvent
public class KeyEventDemo extends Frame public static void main(String[] args) {
implements KeyListener { new KeyEventDemo();
private TextField tfInput; }
private TextArea taDisplay;
@Override
public KeyEventDemo() { public void keyTyped(KeyEvent e) {
setLayout(new FlowLayout()); taDisplay.append("You have typed " +
e.getKeyChar() + "\n");
add(new Label("Enter Text: ")); }
tfInput = new TextField(10); @Override
add(tfInput); public void keyPressed(KeyEvent e) { }
taDisplay = new TextArea(5, 40); @Override
add(taDisplay); public void keyReleased(KeyEvent e) { }
}
tfInput.addKeyListener(this);
setTitle("KeyEvent Demo");
setSize(400, 200);
setVisible(true;
}
44
3.4. Adapter
• Disadvantages of using XxxListener interfaces:
– Each contains more than 1 method. If we care about only
1, we have to implements all (see previous KeyEvent
example)
many have empty body harder to read & maintain
• To avoid: AWT provides an adapter class for each
listener interface with more than one method
– An adapter class implements empty versions of all its
interface's methods (e.g., MouseAdapter implements
MouseListener)
• To use an adapter, we create a subclass of it, instead
of directly implementing a listener interface
45
Example of using Adapter
Exit the application if
we press close button
public KeyEventDemo() {
setLayout(new FlowLayout()); addWindowListener(new WindowAdapter() {
add(new Label("Enter Text: ")); public void windowClosing(WindowEvent e) {
tfInput = new TextField(10); setVisible(false);
add(tfInput); dispose();
taDisplay = new TextArea(5, 40); System.exit(0);
add(taDisplay); }
});
tfInput.addKeyListener(new KeyAdapter() {
@Override setTitle("KeyEvent Demo"); // "this" Frame sets title
public void keyPressed(KeyEvent e) { setSize(400, 200); // "this" Frame sets initial size
taDisplay.append("You have typed " + setVisible(true); // "this" Frame shows
e.getKeyChar() + "\n"); } //End of Constructor
}
});
46
Quick quiz (1/2)
47
Quick quiz (2/2)
48
Quiz
• Create an AWT
application for what
you have done in the
previous lesson
– The interface will looks
like the pictures
– Users can enter add one
by one Triangle to a list
– Users can save the list
in form of a text file or
binary file, using a
menu with shortcuts.
– Remember to alert
appropriate messages
to users
49
Review