Anda di halaman 1dari 82

Graphical User Interface

yewkh2010

Slide 1

Learning Outcomes
At the end of this topic, students should be able to:

1. Describe GUI packages in Java.


2. Use the containers and widgets to build GUI.
3. Add behavior to the GUI elements.
4. Create multiple windows.

yewkh2010

Slide 2

Pedagogy aspect of this module


Java technology can be used in many ICT, BIS or CS areas such as
networking, artificial intelligence, computer graphics, multimedia
etc.. We will be looking specifically at one of the common Java
technology applications - the graphical user interface (GUI).
This module provides you with the breadth of OOP technology and
is not designed for an overnight digestion. You may find many of
the concepts discussed here overwhelming as we are not going to
discuss them in depth. Hence, you may find this module is worth of
another round(s) of review as your understanding in Java deepens.
You need to have prerequisite understanding of all the basic
concepts of OOP:- inheritance, polymorphism, interface and
abstract, in order to fairly understand this module.

yewkh2010

Slide 3

Standard Classes
1. In Java, every object used is instantiated from a certain class.
a. The class could be written by ourselves.
b. The class could be imported from the Java Development Kit.
2. There are many GUI classes in J2SE so that we can just reuse
those classes for instantiating GUI objects to construct interface.
3. Examples:
a. Creating a button:
JButton button = new JButton(OK);
b. Creating a panel:
JPanel panel = new JPanel();
c. Adding button to panel:
panel.add(button);
yewkh2010

Slide 4

java.awt
1. These standard classes are organized under the following packages:

java.awt in the core JDK.

SWING API In the support package JFC.

2. java.awt is a package. Contains all of the classes for creating GUI and
for painting graphics and images.
3. The root of all AWT
components is the class
Component.

java.awt

Component
Button, Canvas,
TextComponent, Label, etc..

Container

4. All GUI components inherit


from Component or
MenuComponent, which are
both abstract classes.

Window

Frame

Panel

Dialog

Applet

javax.swing

JFrame

yewkh2010

JWindow

JDialog

JApplet

Slide 5

javax.swing
1. AWT provides only basic GUI components.
2. Enhanced GUI components are in a different package:
javax.swing.*
javax. swing

JPanel

JMenuBar
JComponent

AbstractButton

JTextComponent
JLabel

JButton

JTextArea
JTextField

JToggleButton

JCheckBox

yewkh2010

JRadioButton

JPasswordField

Slide 6

awt or swing?
1. Since we have the classes to build GUI in both AWT and
Swing packages, which one do we use?
Answer:
Both.
Jcomponents for most widgets are from the Swing package.
Containers such as JFrame, JWindows
extends classes from AWT.
2. How? Simply import both the packages in our coding.
import java.awt.*;
import javax.swing.*;

yewkh2010

Slide 7

Composition of a Java Technology GUI


A Java Technology GUI is composed of
the following elements:
1.

Containers are in the top GUI


containment hierarchy serves to
contain GUI components.

2.

Components are objects derived


from the JComponent class. Also
known as the widgets.

3.

Layout Managers provide


automatic layout of the components.

(Image taken from Sun Microsystem SL275 SE6 textbook)

yewkh2010

Slide 8

Demo
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

import java.awt.*;
import javax.swing.*;
public class HelloGUI {
JFrame myFrame;
JLabel myLabel;
Container myPane;
public HelloGUI() {
myFrame = new JFrame("Hello GUI");
myPane = myFrame.getContentPane();
myLabel = new JLabel("Hello Java GUI! Welcome to my life.");
}
public void launchFrame(){
myPane.add(myLabel);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
public static void main(String[] args) {
HelloGUI myHelloGUIObject = new HelloGUI();
myHelloGUIObject.launchFrame();
}
}

yewkh2010

Slide 9

How to create a GUI in Java


Steps:
1. Declare the class fields of the GUI elements
needed:
a. Containers: ?
b. Widgets: ?
2. Initiate elements in the constructor of the class
(=instantiation of the GUI objects).
3. Assemble the widgets in the containers.
4. Launch the application.
yewkh2010

Slide 10

A SIMPLE EXAMPLE
Create the following GUI:

yewkh2010

Slide 11

UML

MyGUI
-myFrame: JFrame
-myPane: Container
-myPanel: JPanel
-myButton1: JButton
-myButton2: JButton
+MyGUI()
+createAndShowGUI(): void

Instantiate the
objects.

Assemble and
show the objects.

We also want to make this class the application entry


class. How?
yewkh2010

Slide 12

Code Explained
1.

import java.awt.*;

1.

2.

import javax.swing.*;

2.

public void createAndShowGUI(){


myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

3.

3.

public class MyGUI {

4.

private JFrame myFrame;

5.

private Container myPane;

6.
7.

5.
myPanel.setBackground(Color.YELLOW);

7.

myPanel.add(myButton1);

private JPanel myPanel;

8.

myPanel.add(myButton2);

private JButton myButton1, myButton2;

9.

public MyGUI() {

10.

myFrame = new JFrame("My Window");

11.

myPane = myFrame.getContentPane();

12.

myPanel = new JPanel();

13.

10.

myFrame.pack();

11.

myFrame.setVisible(true);

12.

13.

public static void main(String[] args) {

14.

myGUI myDemo = new myGUI();

15.

myDemo.createAndShowGUI();

14.

myButton1 = new JButton("Button 1");

16.

15.

myButton2 = new JButton("Button 2");

17.

16.

myPane.add(myPanel);

6.

8.
9.

4.

}
}

yewkh2010

Slide 13

Code Explained

1. Create frame from JFrame.


2. Acquire content pane from the frame.
3. Create panel from JPanel.
4. Create and add widget(s) to the panel.
5. Add the panel to the pane.

yewkh2010

Slide 14

Important Methods Used


1. setDefaultLookAndFeelDecorated(true)

Applies decorative

borders and window titles to frames.


So that
the program will exit when the close button is clicked.

2. setDefaultCloseOperationJFrame.EXIT_ON_CLOSE)

3. pack()

Causes the JFrame to be sized to fit the preferred size.

4. setVisible(true)

Makes the JFrame visible.

JButton is added to the content pane, not to


the JFrame directly.

5. add(myButton)

yewkh2010

Slide 15

Containers
1.

You need containers to contain the widgets.

2.

In Java, you need to set up 3 container-related items before you


can start adding widgets to your application:
a. A frame
b. A pane.
c. A panel

yewkh2010

Slide 16

Containers

(Image taken from Sun Microsystem SL275 SE6 textbook)


(Image taken from Sun Microsystem SL275 SE6 textbook)

What is the difference between the frame, the


pane, and the panel?

yewkh2010

Slide 17

Containers
Frame is a basic window
that typically has
decorations: the border, a
title, and buttons for
closing or iconifying the
window.
Pane is the visible area
on the frame where we
place the widgets.
Panel is an intermediate
container which must be
placed in another
container such as frame.
It can hold more than one
widgets.
yewkh2010

1. We place widgets onto a


panel.
2. We then place the panel
onto a pane.
3. The pane sits on a frame.
Slide 18

Analogy
Panels.

This window has a


wooden frame.
Pane is the seethrough area on the
window.

Panels.

yewkh2010

Slide 19

Hierarchy of the Containers

(image courtesy of Sun Microsystem)

1.

JrootPane object is created when one of the top-level Swing containers:- JFrame,
JinternalFrame, JApplet and JDialog is instantiated.

2.

The basics of using root panes are:


a.

Get the content pane from the top-level Swing container.

b.

Set the layout manager.

c.

Add Swing components (e.g.: panel(s) or widget(s)) to it.

yewkh2010

Slide 20

getContentPane method
1.
2.
3.
4.

In Java, frame is instantiated from JFrame.


This automatically creates the content pane.
The getContentPane retrieves the content pane object
from the frame.
E.g.:
JFrame myFrame = new JFrame(Login);
Container myContentPane = myFrame.getContentPane();

5.
6.

We need to retrieve the content pane because this is


where we place the other containers and widgets.
For example, we can place the panel(s) on the content
pane.

yewkh2010

Slide 21

Panel Example
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Demo_Panel {
5.
private JFrame myFrame;
6.
private Container myPane;
7.
private JPanel myPanel1,myPanel2;
8.
9.
public Demo_Panel() {
10.
myFrame = new JFrame("My Window");
11.
myPane = myFrame.getContentPane();
12.
myPanel1 = new JPanel();
13.
myPanel2 = new JPanel();
14.
}
15. //see next page

yewkh2010

Slide 22

Panel Example
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
yewkh2010

//from previous page


public void createAndShowGUI(){
myFrame.setLayout(null);
myFrame.setSize(215,245);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPane.setBackground(Color.BLACK);
myPanel1.setSize(200,100);
myPanel1.setBackground(Color.RED);
myPanel1.setLocation(5, 5);
myPanel2.setSize(200,100);
myPanel2.setBackground(Color.YELLOW);
myPanel2.setLocation(5,110);
myPane.add(myPanel1);
myPane.add(myPanel2);
myFrame.setVisible(true);
}
public static void main(String[] args) {
Demo_Panel myDemo = new Demo_Panel();
myDemo. createAndShowGUI();
}
Slide 23

Widgets
1.

Examples of widgets are: JButton, JCheckbox, JRadiobutton, JTextArea, etc.

2.

There are Java classes corresponding to the different widgets.

3.

All the widgets in Java extend the Jcomponent class. Hence, they all share some
common properties:
a.

Border getBorder();

b.

void setBorder(Border b);

c.

void setBackground(Color bg);

d.

void setForeground(Color bg);

e.

void setFont(Font f);

f.

void setOpaque(Boolean isOpaque);

g.

void setMaximumSize(Dimension d);

h.

void setMinimumSize(Dimension d);

i.

void setAlignmentX(float ax);

j.

void setAlignentY(float ay);

k.

void setPreferredSize(Dimension ps);

yewkh2010

Slide 24

JLabel
1. JLabel myLabel1 = new JLabel(Hello);
2. panel.add(myLabel1);
3. myLabel1.setName(Login name:);

yewkh2010

Slide 25

JTextField
1.
2.
3.

yewkh2010

JTextField textField;
textField = new JTextField(jTextField1");
panel.add(textField);

Slide 26

JCheckBox
1.
2.
3.
4.
5.
6.
7.

yewkh2010

JCheckBox checkbox1, checkbox2;


checkbox1 = new JCheckBox(jCheckBox1);
checkbox1.addActionListener(this);
panel.add(checkbox1);
checkbox2 = new JCheckBox(jCheckBox2");
checkbox2.addActionListener(this);
panel.add(checkbox2);

Slide 27

JRadioButton
1.
2.
3.
4.
5.
6.
7.

yewkh2010

JRadioButton radiobox1, radiobox2;


radiobox1 = new JRadioButton(jRadioButton1");
radiobox1.addActionListener(this);
panel.add(radiobox1);
radiobox2 = new JRadioButton(jRadioButton2");
radiobox2.addActionListener(this);
panel.add(radiobox2);

Slide 28

ButtonGroup
1.
2.
3.
4.
5.
6.
7.

yewkh2010

ButtonGroup bg1, bg2;


bg1 = new ButtonGroup(); bg2 = new ButtonGroup();
bg1.add(radiobox1);
bg1.add(radiobox2);
bg1.add(radiobox3);
bg2.add(radiobox4);
bg2.add(radiobox5);

Slide 29

Combo Box
1.
2.
3.

yewkh2010

private String[] s1 =
{"None","Diploma","Bachelor","Master",PhD"};
cb1 = new JComboBox(s1);
cb1.setSelectedItem("None");

Slide 30

Scrollpane
1.
2.

a = new JTextArea();
scrol = new JScrollPane(a);

JTextArea
JScrollPane

yewkh2010

Slide 31

Adding Widgets to the Panel


Try running the below code. What is the expected output?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.

import java.awt.*;
import javax.swing.*;
public class AddMultipleWidgets{
JFrame myFrame;
JButton myButton;
JButton myButton2;
Container myPane;

The code does not generate


output similar to below.

public AddMultipleWidgets() {
myFrame = new JFrame(Login");
myButton = new JButton(Login");
myButton2 = new JButton(Clear");
myPane = myFrame.getContentPane();
}
public void createAndShowGUI(){
myPane.add(myButton);
myPane.add(myButton2);
myFrame.pack();
myFrame.setVisible(true);
}

What should be done to depict


both the buttons?

public static void main(String[] args) {


AddMultipleWidgets demo = new AddMultipleWidgets();
demo.createAndShowGUI();
}
}

yewkh2010

Slide 32

Answer
1.
2.

import java.awt.*;
import javax.swing.*;

3.

public class AddMultipleWidgets{

4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

18.

public void createAndShowGUI(){

19.

myPane.add(myPanel);

20.

myPanel.add(myButton);

21.

myPanel.add(myButton2);

JFrame myFrame;
JButton myButton;
JButton myButton2;
Container myPane;
JPanel myPanel;

22.

myFrame.pack();

23.

myFrame.setVisible(true);

public AddMultipleWidgets() {
myFrame = new JFrame(Login");
myButton = new JButton(Login");
myButton2 = new JButton(Clear");
myPane = myFrame.getContentPane();
myPanel = new JPanel();
}

26.

yewkh2010

24.

25.
public static void main(String[] args) {

27.

AddMultipleWidgets Demo

28.

= new AddMultipleWidgets();

29.

Demo. createAndShowGUI();

30.
31.

}
}

Slide 33

Layout Manager
1.

In Java, to arrange widgets onto a panel, we enlist the help of layout


managers.

2.

Who are these layout managers?


Answer: Objects whose job to manage layout of widgets.

3.

The default layout manager of the panel container is an instance of the


FlowLayout class. This manager lay things out in a sequential order from left
to right.

4.

The default layout manager of the frame container is an instance of the


BorderLayout class. This manager maintains the interface as regions whereby
each region can only accommodate one component.

yewkh2010

Slide 34

Customizing the Layout Manager


5. We can customize the layout manager for the container:
a. To change the layout to Flow layout
myFrame.setLayout(new FlowLayout());
b. To change the layout to Border layout,
myFrame.setLayout(new BorderLayout());
c.

To change the layout to Grid layout


myFrame.setLayout(new GridLayout());

d. To change the layout to Box layout


myFrame.setLayout(new BoxLayout());
e. To change the layout to Card layout
myFrame.setLayout(new CardLayout());

yewkh2010

Slide 35

BorderLayout
1. BorderLayout is the default layout of the frame. Hence dont have to set
the layout.
2. The frame is divided into 5 regions:- CENTER, PAGE_START,
PAGE_END, LINE_START, and LINE_END.

3. Each region can store only one component. For example, if I try to
add more than one button in any one region, only the last added
button will be shown.

yewkh2010

Slide 36

FlowLayout
1.

Panel container default layout is flow layout.

2.

However, on the frame container, flowLayout is not default.

3.

Hence have to set the layout explicitly if we want the frame to have flow
layout instead of borderlayout.

4.

Example:
myFrame.setLayout(new FlowLayout());

5.

Typical feature of flow layout is more than one widgets will be


automatically rearranged in the container should there be any resize. The
order of arrangement is left to right and top-down.

yewkh2010

Slide 37

GridLayout
1.

GridLayout is not the default layout of the frame. Hence have to set the
layout explicitly.

2.

Syntax:
SetLayout(new GridLayout(int rows, int cols));

3.

Examples:

yewkh2010

Slide 38

GridBagLayout
1. Similar to a grid layout, but provides a wide variety of options
for resizing and positioning the components.
2. For further details, read the J2SE API on GridBagLayout.

yewkh2010

Slide 39

GridBagLayout
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
JButton button;
pane.setLayout(new GridBagLayout());

c.gridy = 0;
pane.add(button, c);

GridBagConstraints c = new GridBagConstraints();

button = new JButton("Button 3");


//natural height, maximum width

c.fill = GridBagConstraints.HORIZONTAL;

c.fill = GridBagConstraints.HORIZONTAL;

c.weightx = 0.5;

button = new JButton("Button 1");


c.weightx = 0.5; //request any extra horizontal space
c.fill = GridBagConstraints.HORIZONTAL;

c.gridx = 2;
c.gridy = 0;
pane.add(button, c);

c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
yewkh2010

Slide 40

GridBagLayout
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;

//reset to default

c.weighty = 1.0; //request any extra vertical space


button = new JButton("Long-Named Button 4");

c.anchor = GridBagConstraints.PAGE_END;
//bottom of space

c.fill = GridBagConstraints.HORIZONTAL;

c.insets = new Insets(10,0,0,0); //top padding

c.ipady = 40;

c.gridx = 1;

//make this component tall

//aligned with button 2

c.weightx = 0.0;

c.gridwidth = 2; //2 columns wide

c.gridwidth = 3;

c.gridy = 2;

c.gridx = 0;

pane.add(button, c);

//third row

c.gridy = 1;
pane.add(button, c);

yewkh2010

Slide 41

BoxLayout
import java.awt.Component;

private static void launchGUI() {

import java.awt.Container;

//Create and set up the window.

import javax.swing.BoxLayout;

JFrame frame = new JFrame("BoxLayoutDemo");

import javax.swing.JButton;

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

import javax.swing.JFrame;
//Set up the content pane.
public class BoxLayoutDemo {

addComponentsToPane(frame.getContentPane());

public static void addComponentsToPane(Container pane) {

//Display the window.

pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

frame.pack();
frame.setVisible(true);

addAButton("Button 1", pane);

addAButton("Button 2", pane);


addAButton("Button 3", pane);

public static void main(String[] args) {

addAButton("Long-Named Button 4", pane);

launchGUI();

addAButton("5", pane);
}

}
}

private static void addAButton(String text, Container container) {


JButton button = new JButton(text);

The above code generates Box Layout arrangement of buttons. Run


and study the code.

button.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(button);
}

yewkh2010

Slide 42

Turn off the Layout Manager


1.

Layout manager is automatic and turned on by default.

2.

Sometimes this can be a nuisance as that prevents us from customizing the


location, size and bounds of the components to the exact specifications that we
want.

3.

We can turn off the automatic layout of any of the containers:


myFrame.setLayout(null);
myPane.setLayout(null);
myPanel.setLayout(null);

4.

Example:
JFrame myFrame = new JFrame(My Software);
myFrame.setLayout(null);
myFrame.setSize(400,300);

5.

Note: This approach of disabling LayoutManager is not preferred. In OOP, a


better way of doing is to create a new subclass of LayoutManager.

yewkh2010

Slide 43

Example

Create a Java technology GUI similar to above without the


use of any layout manager.

yewkh2010

Slide 44

Example
1.

import java.awt.*;

20.

myPane.setBackground(Color.BLUE);

2.

import javax.swing.*;

21.

myPanel.setLayout(null);

22.

myPanel.setSize(300,200);

23.

myPanel.setLocation(50,50);

24.

myPanel.setBackground(Color.GREEN);

3.

public class AddOneWidget_NullLayout{

4.

JFrame myFrame;

5.

Container myPane;

26.

myButton.setSize(100,30);

6.

JButton myButton;

27.

myButton.setLocation(100,85);

7.

JPanel myPanel;

28.

myPane.add(myPanel);

29.

myPanel.add(myButton);

8.
9.

public AddOneWidget_NullLayout() {

10.
11.

myFrame = new JFrame("Demo");


myPane =
myFrame.getContentPane();

12.

myPanel = new JPanel();

13.

myButton = new JButton("Exit");

14.

30.
31.

myFrame.setVisible(true);

32.

33.
34.

public static void main(String[] args) {

35.

AddOneWidget_NullLayout myDemo = new


AddOneWidget_NullLayout();

36.

myDemo.createAndShowGUI();

37.

15.
16.

25.

38.

}
}

public void createAndShowGUI(){

17.

myFrame.setLayout(null);

18.

myFrame.setSize(400,330);

19.

yewkh2010

Slide 45

Good OOP practice


1.
2.

What we have done so far is to build the Java technology GUI in a single class.
Below depicts the expected output and the corresponding UML describing the
design of the class.
MyWindow
-f: JFrame
-pane: Container
-panel: JPanel
-button1: JButton
+MyWindow()
+createAndShowGUI(): void
+public static main(String [] args): void

Declare attributes for


class.
Initiate components.
Assemble components.
Instantiate MyWindow and
launch the program.

3.

The solution does not necessary has to be in a single class.

yewkh2010

Slide 46

Good OOP practice


2.

A better practice is to separate both widgets and intermediary containers (such as panel)
from the launcher which initializes frame into two separate classes. For example:
a.

MyGUI class instantiate and assemble panel(s) with the widgets.

b.

MyApp class the launcher class that instantiate the frame and later call getPanel().
Declare attributes for
class.

MyWindow
-f: JFrame
-pane: Container
-panel: JPanel
-button1: JButton

Initiate components.

+MyWindow()
+createAndShowGUI(): void
+public static main(String [] args): void

Assemble components.
Instantiate MyWindow and
launch the program.

Declare attributes for


class.

MyGUI

MyApp

-panel: Jpanel
-button1: JButton

-f: JFrame
-pane: Container

Instantiate frame.
Call getPanel() method
from MyGUI object.
Launch the frame.

yewkh2010

+public static main(String [] args): void

<<Uses>>

+MyGUI()
+getPanel(): JPanel

Declare attributes for


class.
Initiate components.
Then assemble.

Return assembled panel


and widgets.

Slide 47

The GUI class


1.

import javax.swing.*;

2.
3.
4.
5.

public class MyGUI


{
JButton button1;
JPanel panel;

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

public MyGUI()
{
button1 = new JButton(Exit");
panel = new JPanel();
panel.add(button1);
}
JPanel getPanel()
{
return panel;
}

Declare attributes for


class.

Initiate components.
Then assemble.

Return assembled panel


and widgets.

yewkh2010

Slide 48

The Application Class


1.
2.

import javax.swing.*;
import java.awt.*;

3.
4.

public class MyApp


{

5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

Resides in

Resides in

public static void main(String[] args)


{
JFrame myFrame = new JFrame("Demo");
Container myPane = myFrame.getContentPane();

Initialize JFrame
object with parameter
Demo.
Use JFrame method
to retrieve the
content pane.
Instantiate the other
class MyGUI as
object.

MyGUI myGUIObject = new MyGUI();


JPanel myPanel = myGUIObject.getPanel();
Call getPanel()
myPane.add(myPanel);
method in MyGUI
myFrame.pack();
object
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}

yewkh2010

Slide 49

JOptionPane
1. JOptionPane class is available under the package javax.swing.
2. It is used to provide GUI that solicits user input.
3. There are various methods under the JOptionPane class:
a. showMessageDialog();
b. showConfirmDialog();
c. showInputDialog();
d. showOptionDialog();
4. The following slides are several examples of the usage.

yewkh2010

Slide 50

Show Message Dialog


1.

JOptionPane.showMessageDialog(null,"Java uses JOGL package to


render 3D graphics on graphic cards.");

2.

JOptionPane.showMessageDialog(null,"A class can inherit from only


one super class.","Inheritance",JOptionPane.WARNING_MESSAGE);

3.

JOptionPane.showMessageDialog(null,"The polymorphed object should


always be more specialized or equal to the variable type",
"Polymorphism", JOptionPane.ERROR_MESSAGE);

yewkh2010

Slide 51

Show Option Dialog


Object[] options = {"AWT", "JMF", "JNI"};
int ans = JOptionPane.showOptionDialog(null, "Java allows
usage of C code using ...?",
"Trivia",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);

yewkh2010

Slide 52

Show Confirm Dialog


int ans2 = JOptionPane.showConfirmDialog(null,
"Old name of Java is Oak.",
"Trivia",
JOptionPane.YES_NO_OPTION);

yewkh2010

Slide 53

Show Input Dialog


String ans3 = JOptionPane.showInputDialog("A class may
extend another class but implements an ");

yewkh2010

Slide 54

Event Listening & Handling

What happens if you try to click the Exit button from the
earlier example? Is there any response after we click the
button?
Answer: No. Because we have not yet registered the
listener and handler to the event source!

yewkh2010

Slide 55

Event Listening & Handling


1.

CLICK EVENT

2.

JVM

ActionListener
3.
4.
5.

Take action!!!!
Do something!!!

Event source automatically generates an event


when invoked.Examples:
a.
A button click or selecting a menu item
ActionEvent
b. A mouse click or movement
MouseEvent
c.
A frame is closed or iconified
WindowEvent
Unfortunately, the components (both containers
and widgets) are unable to detect WHEN these
events are invoked unless we do something
We must add a listener (register event listener)
to the GUI component.
How?
Use addActionListener() method.
We also need to tell the GUI component how to
respond if it hears the event. How?
a.
Create one or more handlers.
b. Pass the handler as a parameter in
addActionListener() method. Example:
addActionListener(myEventHandler)

yewkh2010

Slide 56

Event Listening & Handling


Before the coding

After the coding

What should I listen


to?

Oh.. I should listen to


this button click

If I hear it, then what


should I do?

JAVA

yewkh2010

Then, I must
immediately execute
the handler.

JAVA

Slide 57

Quiz yourself
1. What is an event source? Give a few examples.
2. What is an event? Give a few examples.
3. Why do we add listeners to the components?
4. Who should listen to whose event?
5. Why dont we make the event source automatically listens to the
event instead of using methods of adding the listener explicity?
6. What should the program respond to the event? Take action?
What action? How?
7. What is the handler, really?

yewkh2010

Slide 58

Event Handler
1. The event handler object is instantiated from the handler
class that implements the listener interface.
2. The handler class must contain all overriding method for the
interface, such as public void actionPerformed(ActionEvent event){}

yewkh2010

<<interface>>
Interface01
+method01():void

<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

MyClass
+method01():void

MyClass
+actionPerformed(ActionEvent event):void

Generic Interface
Implementation

Implementing
ActionListener inteface

Slide 59

Event Handler
Two flavors of implementations:
GUI and handler in the same class.
GUI and handler in separate classes.
<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

<<interface>>
ActionListener
+actionPerformed(ActionEvent event):void

MyGUIClass
+actionPerformed(ActionEvent event):void

MyActionHandler
+actionPerformed(ActionEvent event):void

<<uses>>

MyGUI
+method1():void

yewkh2010

Slide 60

Event Handling
There can be one or
multiple handlers for
one single event.

(Image & content taken from


Sun Microsystem SL275 SE6
textbook)

yewkh2010

Slide 61

1.
2.
3.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

4.
5.
6.

public class MyActiveGUI implements ActionListener {


JButton button1;
JPanel panel;

7.
8.
9.
10.
11.
12.
13.

public MyActiveGUI() {
button1 = new JButton(Exit);
button1.addActionListener(this);
panel = new JPanel();
panel.add(button1);
}
JPanel getPanel() { }

14.
15.
16.
17.
18.
19.
20.
21.
22.

public void actionPerformed(ActionEvent ae) {


JButton but = (JButton) ae.getSource();
String labelOnBut = but.getText();
if (labelOnBut.equals(Exit)) {
System.out.println(Program terminated.");
System.exit(1);
}
}

Abide to a contract:
You will be recognized as a
listener.
You will get notification.
But you must implement a
method that
acts upon the notification.

Refers to the current object. The


current object is the handler
because it implements the
ActionListener.

This method you must


define when you
implements ActionListener

yewkh2010

Slide 62

Adding Behavior to More than One Buttons


What should I do to make the program respond to
different buttons when clicked?

yewkh2010

Slide 63

Adding Behavior to More than One Buttons


1.
2.
3.
4.

import
import
import
import

5.

public class MultipleButtons implements


ActionListener {
JFrame myFrame;
Container myPane;
JPanel myPanel;
JButton loginButton;
JButton clearButton;
JButton exitButton;

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

javax.swing.*;
javax.swing.JOptionPane;
java.awt.*;
java.awt.event.*;

public MultipleButtons(){
myFrame = new JFrame("Event Handling
Demo");
myPane = myFrame.getContentPane();
myPanel = new JPanel();
loginButton = new JButton("Login");
loginButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
}
public void createAndShowGUI(){
myPanel.add(loginButton);
myPanel.add(clearButton);
myPanel.add(exitButton);
myPane.add(myPanel,BorderLayout.PAGE_END);
myFrame.pack();
myFrame.setVisible(true);
}

yewkh2010

33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.

54.
55.
56.
57.

public static void main(String [] args){


MultipleButtons myDemo = new
MultipleButtons();
myDemo.createAndShowGUI();
}
public void actionPerformed(ActionEvent

ae){

JButton but = (JButton) ae.getSource();


String labelOnBut = but.getText();
if (labelOnBut.equals("Login")) {
//perform login function
JOptionPane.showMessageDialog(myFrame,"Login
successful");
}
if (labelOnBut.equals("Clear")) {
//perform textfield and password
field clearing function
JOptionPane.showMessageDialog(myFrame,"Please
key in again.");
}
if (labelOnBut.equals("Exit")) {
int response =
JOptionPane.showConfirmDialog(myFrame, "Are you
sure?", "Confirmation",
JOptionPane.YES_NO_OPTION);
if (response==0)System.exit(0);
}
}
}

Slide 64

getSource() method
1.

Example:
JButton but = (JButton) ae.getSource();

2.

3.

getSource() returns a Component object.


Component is a general data type, eg. Human is a general
data type for student.
But unfortunately too general. Hence we need to cast to
specify further.
Example:
(JButton) cast the datatype to another type JButton.

yewkh2010

Slide 65

Adding Behavior to Widget


1.
2.

public void actionPerformed(ActionEvent ae)


{

3.

Object comp = ae.getSource();

4.
5.
6.
7.
8.

if (comp instanceof JButton)


{
JButton but = (JButton) comp;
if (but == button1)
{
System.out.println("Entered: " +
textField.getText()); }
}

9.
10.

yewkh2010

Slide 66

Adding Multiple Behaviors to One Component


1.

We can add multiple behaviors to one component.

2.

This is done by simply implementing more interface and adding more handlers.

Category

Interface

Methods to be implemented

Action

ActionListener

actionPerformed(ActionEvent)

Item

ItemListener

itemStateChanged(ItemEvent)

Mouse

MouseListener

mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)

Mouse motion

MouseMotionListener

mouseDragged(MouseEvent)
mouseMoved(MouseEvent)

Key

KeyListener

keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)

Mouse wheel

MouseWheelListener

mouseWheelMoved(MouseWheelEvent e)

Text

TextListener

textValueChanged(TextEvent)

yewkh2010

Slide 67

Adding Multiple Behaviors to One Component

The above GUI listens to the mouse motion and mouse clicks.

yewkh2010

Slide 68

Adding Multiple Behaviors to One Component


1.

import javax.swing.*;

25.

public void mouseEntered(MouseEvent e) {

2.

import java.awt.*;

26.

String s = "The mouse entered";

3.

import java.awt.event.*;

27.

tf.setText(s);

28.

4.

public class MultipleBehaviors implements MouseMotionListener, MouseListener {

5.

private JFrame f;

29.

public void mouseExited(MouseEvent e) {

6.

private JTextField tf;

30.

String s = "The mouse has left the building";

31.

tf.setText(s);

32.

33.

// Unused MouseMotionListener method.

7.

public MultipleBehaviors() {

8.

f = new JFrame("Two listeners example");

9.

tf = new JTextField(30);

10.

34.

public void mouseMoved(MouseEvent e) { }

11.

public void launchFrame() {

35.

// Unused MouseListener methods.

12.

JLabel label = new JLabel("Click and drag the mouse");

36.

public void mousePressed(MouseEvent e) { }

13.

f.add(label, BorderLayout.NORTH);

37.

public void mouseClicked(MouseEvent e) { }

14.

f.add(tf, BorderLayout.SOUTH);

38.

public void mouseReleased(MouseEvent e) { }

15.

f.addMouseMotionListener(this);

16.

f.addMouseListener(this);

39.

public static void main(String args[]) {

17.

f.setSize(300, 200);

40.

MultipleBehaviors two = new MultipleBehaviors();

18.

f.setVisible(true);

41.

two.launchFrame();

42.

43.

19.

20.

// These are MouseMotionListener events

21.

public void mouseDragged(MouseEvent e) {

22.

String s = "Mouse dragging: X = " + e.getX() + " Y = " + e.getY();

23.

tf.setText(s);

24.

yewkh2010

Slide 69

Summary of event listening and handling


Steps to do:
1. Event listening and handling are contained in java.awt.event,
hence not to forget the need to import the package into our code.
Identify the event source.
2. Create the event handler(s).
3. Register listener to the GUI component (usually the event source
itself).
4. Pass the event handler as the parameter in the addActionListener
method.

yewkh2010

Slide 70

Steps to create multiple windows

1. Create different GUI classes, each with different


Jcomponents as needed.
2. Create one application class GUI that contains
the main method.
3. Instantiate the GUI objects from the GUI
classes in the application class.
4. Set visibility to be true when displaying the
window, and false when hiding the window.
Use frame.setVisible(boolean) method to
achieve the purpose.
yewkh2010

Slide 71

Multiple Windows
WindowMain.java

Window0.java

Window1.java

Lets walkthrough the UML and the Java code.


yewkh2010

Slide 72

Window0.java
Window0

Declare fields for the


widgets and containers.

-//declare all the required WIDGET variables here


-//declare all the required CONTAINER variables here
+Window0()
+showFrame(): void
+hideFrame(): void

Instantiate the widget/container


objects in the constructor.
Assemble them using add
method.

Pass true parameter to


setVisible method.
Pass false parameter to
setVisible method.
Study line by line the java code in Window0.java while
referring to the above UML.
yewkh2010

Slide 73

Window0.java
1.

import javax.swing.*;

2.

import java.awt.*;

3.

import java.awt.event.*;

4.
5.

public class Window0

6.

21.

public void showFrame() {

22.

frame.setVisible(true);

23.

24.
25.

7.

private JButton button0, button1;

8.

private JPanel

9.

private JFrame frame;

panel;

public void hideFrame(){

26.

frame.setVisible(false);

27.
28.

}
}

10.
11.

public Window0(String frameName){

12.

panel = new JPanel();

13.

button0 = new JButton("OK"); panel.add(button0);

14.

button1 = new JButton("Cancel"); panel.add(button1);

15.

frame = new JFrame(frameName);

16.

Container pane = frame.getContentPane();

17.

pane.add(panel);

18.

frame.pack();

19.

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

20.

yewkh2010

Create the frame


object here (not in
the main class!)

Slide 74

Window1.java
Window1

Declare fields for the


widgets and containers.

-//declare all the required WIDGET variables here


-//declare all the required CONTAINER variables here
+Window1()
+showFrame(): void
+hideFrame(): void

Instantiate the widget/container


objects in the constructor.
Assemble them using add
method.

Pass true parameter to


setVisible method.

Study line by line the java code in Window1.java while


referring to the above UML.
Similar to Window1 except that different widgets are
instantiated and assembled differently in the constructor.
yewkh2010

Pass false parameter to


setVisible method.

Slide 75

Window1.java
1.

import javax.swing.*;

2.

import java.awt.*;

3.

import java.awt.event.*;

4.
5.

public class Window1{

8.

private JButton button;

9.

private JTextField tf;

10.

private JPanel

13.

private JFrame frame;

panel;

14.
15.

25.
26.

public void showFrame(){

27.

frame.setVisible(true);

28.

29.
30.

public void hideFrame(){

31.

frame.setVisible(false);

32.
33.

}
}

public Window1(String frameName){

16.

panel = new JPanel();

17.

button = new JButton("OK"); panel.add(button);

18.

tf = new JTextField(10); panel.add(tf);

19.

frame = new JFrame(frameName);

20.

Container pane = frame.getContentPane();

21.

pane.add(panel);

22.

frame.pack();

23.

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

24.

yewkh2010

Pretty much the


same as
Window0.java

Slide 76

WindowMain.java
MyGUI_WindowMain <<implements ActionListener>>
-//declare all the required WIDGET fields here
-//declare all the required CONTAINER fields here
~//declare MyGUI_Window0 field here
~//declare MyGUI_Window1 field here
+MyGUI_WindowMain()
+actionPerformed(ActionEvent ae): void
<<static>>+main(String [] args): void

Main method makes this class an application class. Hence,


this class is launched first everytime we run the
application.
As usual, use method showFrame() to launch the GUI.

Study line by line the java code in WindowMain.java


while referring to the above UML.
yewkh2010

This class object becomes an


action listener by implementing
ActionListener.

Declare the fields for the


two new windows that we
are about to create.

Along with other widgets,


instantiate the objects for
both Window0 field and
Window1 field.
WindowMain MUST add and
define the method
actionPerformed since it
implements the ActionListener
(an interface)
Slide 77

WindowMain.java
1.

import javax.swing.*; import java.awt.*; import java.awt.event.*;

2.
3.

public class WindowMain implements ActionListener{

4.

private JButton button0, button1;

5.

private JPanel

6.

private JFrame frame;

7.

Window0 win1;

8.

Window1 win2;

panel;

Add Window0 and


Window1 variables

9.
10.

public WindowMain(String frameName){

11.

panel = new JPanel();

12.

button0 = new JButton("Show Window 0"); button0.addActionListener(this);

13.

panel.add(button0);

14.
15.

button1 = new JButton("Show Window 1");button1.addActionListener(this);

16.

panel.add(button1);

17.

frame = new JFrame(frameName);

18.

Container pane = frame.getContentPane(); pane.add(panel);

19.

frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

20
21.

win1 = new Window0("Window 1");

22.

win2 = new Window1("Window 2");

yewkh2010
23. }

Create instances of
Window0 and Window1,
but don't show yet!

Slide 78

WindowMain.java
24.
25.

public void actionPerformed(ActionEvent ae){

26.

JButton jb = (JButton) ae.getSource();

27.

if (jb == button0){

28.

win1.showFrame();

29.

win2.hideFrame();

30.

31.

else if (jb == button1){

32.

win2.showFrame();

33.

win1.hideFrame();

34.
35.

Event handling
for both the
buttons.

}
}

36.
37.

public static void main(String args[]){

38.

WindowMain wm = new WindowMain("Main Window");

39.

wm.showFrame();

40.

41. }

yewkh2010

Slide 79

Summary
1.
2.
3.
4.
5.
6.
7.

The GUI packages in Java are in java.awt and javax.swing.


There are different types of containers. A standalone application
has JFrame as its main container.
Different container has different layout managers. Layout
managers determine how widgets are arranged in the container.
Panel container can be used to display more than one widget.
Commonly-used widgets are JButton, JTextField and JTextArea.
Widgets and containers generate events, e.g.: keyboard presses,
mouse clicks, mouse motions, change of input values, etc.
The purpose of Event handling is to determine how the
program should respond when an event is generated.

yewkh2010

Slide 80

Q&A

yewkh2010

Slide 81

Extra Reading
Read up javadoc on java.awt.Toolkit.

yewkh2010

Slide 82

Anda mungkin juga menyukai