82
Slide 1 yewkh©2010 Graphical User Interface

OOP 14 GUI DetailedReferenceSlides

  • Upload
    jesse

  • View
    220

  • Download
    0

Embed Size (px)

DESCRIPTION

GUI

Citation preview

Page 1: OOP 14 GUI DetailedReferenceSlides

Slide 1yewkh©2010

Graphical User Interface

Page 2: OOP 14 GUI DetailedReferenceSlides

Slide 2yewkh©2010

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

Learning Outcomes

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.

Page 3: OOP 14 GUI DetailedReferenceSlides

Slide 3yewkh©2010

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.

Page 4: OOP 14 GUI DetailedReferenceSlides

Slide 4yewkh©2010

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);

Page 5: OOP 14 GUI DetailedReferenceSlides

Slide 5yewkh©2010

java.awt1. 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.

4. All GUI components inherit from Component or MenuComponent, which are both abstract classes.

javax.swing

java.awt

Container

Window Panel

Frame Dialog Applet

Component

Button, Canvas, TextComponent, Label, etc..

JFrame JDialog JAppletJWindow

Page 6: OOP 14 GUI DetailedReferenceSlides

Slide 6yewkh©2010

javax.swing

1. AWT provides only basic GUI components.

2. Enhanced GUI components are in a different package: javax.swing.*

javax. swing

JComponent

JPanel

AbstractButton

JLabel

JTextComponent

JMenuBar

JTextArea

JTextField

JPasswordField

JButton

JToggleButton

JCheckBoxJRadioButton

Page 7: OOP 14 GUI DetailedReferenceSlides

Slide 7yewkh©2010

1. Since we have the classes to build GUI in both AWT and Swing packages, which one do we use?

2. How? Simply import both the packages in our coding.import java.awt.*;import javax.swing.*;

awt or swing?

Answer:

Both.

Jcomponents for most widgets are from the Swing package.

Containers such as JFrame, JWindows

extends classes from AWT.

Page 8: OOP 14 GUI DetailedReferenceSlides

Slide 8yewkh©2010

Composition of a Java Technology GUI

(Image taken from Sun Microsystem SL275 –SE6 textbook)

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.

Page 9: OOP 14 GUI DetailedReferenceSlides

Slide 9yewkh©2010

Demo1. import java.awt.*;2. import javax.swing.*;3. 4. public class HelloGUI {5. JFrame myFrame;6. JLabel myLabel;7. Container myPane;8. 9. public HelloGUI() {10. myFrame = new JFrame("Hello GUI");11. myPane = myFrame.getContentPane();12. myLabel = new JLabel("Hello Java GUI! Welcome to my life.");13. }14. 15. public void launchFrame(){16. myPane.add(myLabel);17. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);18. myFrame.pack();19. myFrame.setVisible(true);20. }21. 22. public static void main(String[] args) {23. HelloGUI myHelloGUIObject = new HelloGUI();24. myHelloGUIObject.launchFrame();25. } 26. }

Page 10: OOP 14 GUI DetailedReferenceSlides

Slide 10yewkh©2010

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.

Page 11: OOP 14 GUI DetailedReferenceSlides

Slide 11yewkh©2010

A SIMPLE EXAMPLE

Create the following GUI:

Page 12: OOP 14 GUI DetailedReferenceSlides

Slide 12yewkh©2010

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?

Page 13: OOP 14 GUI DetailedReferenceSlides

Slide 13yewkh©2010

1. public void createAndShowGUI(){

2. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

3.

4. myPane.add(myPanel);

5.

6. myPanel.setBackground(Color.YELLOW);

7. myPanel.add(myButton1);

8. myPanel.add(myButton2);

9.

10. myFrame.pack();

11. myFrame.setVisible(true);

12. }

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

14. myGUI myDemo = new myGUI();

15. myDemo.createAndShowGUI();

16. }

17. }

Code Explained1. import java.awt.*;

2. import javax.swing.*;

3. public class MyGUI {

4. private JFrame myFrame;

5. private Container myPane;

6. private JPanel myPanel;

7. private JButton myButton1, myButton2;

8.

9. public MyGUI() {

10. myFrame = new JFrame("My Window");

11. myPane = myFrame.getContentPane();

12. myPanel = new JPanel();

13.

14. myButton1 = new JButton("Button 1");

15. myButton2 = new JButton("Button 2");

16. }

Page 14: OOP 14 GUI DetailedReferenceSlides

Slide 14yewkh©2010

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.

Page 15: OOP 14 GUI DetailedReferenceSlides

Slide 15yewkh©2010

Important Methods Used

1. setDefaultLookAndFeelDecorated(true) – Applies decorative borders and window titles to frames.

2. setDefaultCloseOperationJFrame.EXIT_ON_CLOSE) – So that the program will exit when the close button is clicked.

3. pack() – Causes the JFrame to be sized to fit the preferred size.

4. setVisible(true) – Makes the JFrame visible.

5. add(myButton) – JButton is added to the content pane, not to the JFrame directly.

Page 16: OOP 14 GUI DetailedReferenceSlides

Slide 16yewkh©2010

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 frameb. A pane. c. A panel

Page 17: OOP 14 GUI DetailedReferenceSlides

Slide 17yewkh©2010

What is the difference between the frame, the pane, and the panel?

Containers

(Image taken from Sun Microsystem SL275 –SE6 textbook)(Image taken from Sun Microsystem SL275 –SE6 textbook)

Page 18: OOP 14 GUI DetailedReferenceSlides

Slide 18yewkh©2010

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.

Containers

1. We place widgets onto a panel.

2. We then place the panel onto a pane.

3. The pane sits on a frame.

Page 19: OOP 14 GUI DetailedReferenceSlides

Slide 19yewkh©2010

This window has a wooden frame.

Pane is the see-through area on the window.

Panels.

Panels.

Analogy

Page 20: OOP 14 GUI DetailedReferenceSlides

Slide 20yewkh©2010

Hierarchy of the Containers

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.

(image courtesy of Sun Microsystem)

Page 21: OOP 14 GUI DetailedReferenceSlides

Slide 21yewkh©2010

getContentPane method

1. In Java, frame is instantiated from JFrame.2. This automatically creates the content pane.3. The getContentPane retrieves the content pane object

from the frame.4. E.g.:

JFrame myFrame = new JFrame(“Login”);Container myContentPane = myFrame.getContentPane();

5. We need to retrieve the content pane because this is where we place the other containers and widgets.

6. For example, we can place the panel(s) on the content pane.

Page 22: OOP 14 GUI DetailedReferenceSlides

Slide 22yewkh©2010

Panel Example1. 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

Page 23: OOP 14 GUI DetailedReferenceSlides

Slide 23yewkh©2010

1. //from previous page2. public void createAndShowGUI(){3. myFrame.setLayout(null); 4. myFrame.setSize(215,245); 5. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);6. 7. myPane.setBackground(Color.BLACK);8. 9. myPanel1.setSize(200,100);10. myPanel1.setBackground(Color.RED);11. myPanel1.setLocation(5, 5);12. 13. myPanel2.setSize(200,100);14. myPanel2.setBackground(Color.YELLOW);15. myPanel2.setLocation(5,110);16. 17. myPane.add(myPanel1);18. myPane.add(myPanel2);19. myFrame.setVisible(true);20. }21. 22. public static void main(String[] args) {23. Demo_Panel myDemo = new Demo_Panel();24. myDemo. createAndShowGUI();25. }

Panel Example

Page 24: OOP 14 GUI DetailedReferenceSlides

Slide 24yewkh©2010

Widgets1. 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);

Page 25: OOP 14 GUI DetailedReferenceSlides

Slide 25yewkh©2010

JLabel

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

Page 26: OOP 14 GUI DetailedReferenceSlides

Slide 26yewkh©2010

JTextField

1. JTextField textField;2. textField = new JTextField(“jTextField1");3. panel.add(textField);

Page 27: OOP 14 GUI DetailedReferenceSlides

Slide 27yewkh©2010

JCheckBox

1. JCheckBox checkbox1, checkbox2;2. checkbox1 = new JCheckBox(“jCheckBox1”);3. checkbox1.addActionListener(this);4. panel.add(checkbox1);5. checkbox2 = new JCheckBox(“jCheckBox2");6. checkbox2.addActionListener(this);7. panel.add(checkbox2);

Page 28: OOP 14 GUI DetailedReferenceSlides

Slide 28yewkh©2010

JRadioButton

1. JRadioButton radiobox1, radiobox2;2. radiobox1 = new JRadioButton(“jRadioButton1");3. radiobox1.addActionListener(this);4. panel.add(radiobox1);5. radiobox2 = new JRadioButton(“jRadioButton2");6. radiobox2.addActionListener(this);7. panel.add(radiobox2);

Page 29: OOP 14 GUI DetailedReferenceSlides

Slide 29yewkh©2010

ButtonGroup

1. ButtonGroup bg1, bg2;2. bg1 = new ButtonGroup(); bg2 = new ButtonGroup();3. bg1.add(radiobox1);4. bg1.add(radiobox2);5. bg1.add(radiobox3);6. bg2.add(radiobox4);7. bg2.add(radiobox5);

Page 30: OOP 14 GUI DetailedReferenceSlides

Slide 30yewkh©2010

Combo Box

1. private String[] s1 = {"None","Diploma","Bachelor","Master",“PhD"};

2. cb1 = new JComboBox(s1);3. cb1.setSelectedItem("None");

Page 31: OOP 14 GUI DetailedReferenceSlides

Slide 31yewkh©2010

Scrollpane

1. a = new JTextArea();2. scrol = new JScrollPane(a);

JTextAreaJScrollPane

Page 32: OOP 14 GUI DetailedReferenceSlides

Slide 32yewkh©2010

Adding Widgets to the PanelTry running the below code. What is the expected output?1. import java.awt.*;2. import javax.swing.*; 3. public class AddMultipleWidgets{4. JFrame myFrame;5. JButton myButton;6. JButton myButton2;7. Container myPane;8. 9. public AddMultipleWidgets() {10. myFrame = new JFrame(“Login");11. myButton = new JButton(“Login");12. myButton2 = new JButton(“Clear");13. myPane = myFrame.getContentPane();14. }15. 16. public void createAndShowGUI(){17. myPane.add(myButton);18. myPane.add(myButton2);19. myFrame.pack();20. myFrame.setVisible(true);21. }22. 23. public static void main(String[] args) {24. AddMultipleWidgets demo = new AddMultipleWidgets();25. demo.createAndShowGUI();26. } 27. }

The code does not generate output similar to below.

What should be done to depict both the buttons?

Page 33: OOP 14 GUI DetailedReferenceSlides

Slide 33yewkh©2010

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

3. public class AddMultipleWidgets{

4. JFrame myFrame;5. JButton myButton;6. JButton myButton2;7. Container myPane;8. JPanel myPanel;9. 10. public AddMultipleWidgets() {11. myFrame = new JFrame(“Login");12. myButton = new JButton(“Login");13. myButton2 = new JButton(“Clear");14. myPane = myFrame.getContentPane();15. myPanel = new JPanel();16. }17.

18. public void createAndShowGUI(){19. myPane.add(myPanel);20. myPanel.add(myButton);21. myPanel.add(myButton2);22. myFrame.pack();23. myFrame.setVisible(true);24. }25. 26. public static void main(String[] args) {27. AddMultipleWidgets Demo 28. = new AddMultipleWidgets();29. Demo. createAndShowGUI();30. } 31. }

Page 34: OOP 14 GUI DetailedReferenceSlides

Slide 34yewkh©2010

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.

Page 35: OOP 14 GUI DetailedReferenceSlides

Slide 35yewkh©2010

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());

Page 36: OOP 14 GUI DetailedReferenceSlides

Slide 36yewkh©2010

BorderLayout

1. BorderLayout is the default layout of the frame. Hence don’t 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.

Page 37: OOP 14 GUI DetailedReferenceSlides

Slide 37yewkh©2010

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.

Page 38: OOP 14 GUI DetailedReferenceSlides

Slide 38yewkh©2010

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:

Page 39: OOP 14 GUI DetailedReferenceSlides

Slide 39yewkh©2010

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.

Page 40: OOP 14 GUI DetailedReferenceSlides

Slide 40yewkh©2010

GridBagLayout

JButton button;

pane.setLayout(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();

//natural height, maximum width

c.fill = GridBagConstraints.HORIZONTAL;

button = new JButton("Button 1");

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

c.fill = GridBagConstraints.HORIZONTAL;

c.gridx = 0;

c.gridy = 0;

pane.add(button, c);

button = new JButton("Button 2");

c.fill = GridBagConstraints.HORIZONTAL;

c.weightx = 0.5;

c.gridx = 1;

c.gridy = 0;

pane.add(button, c);

button = new JButton("Button 3");

c.fill = GridBagConstraints.HORIZONTAL;

c.weightx = 0.5;

c.gridx = 2;

c.gridy = 0;

pane.add(button, c);

Page 41: OOP 14 GUI DetailedReferenceSlides

Slide 41yewkh©2010

GridBagLayoutbutton = new JButton("5");

c.fill = GridBagConstraints.HORIZONTAL;

c.ipady = 0; //reset to default

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

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

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

c.gridx = 1; //aligned with button 2

c.gridwidth = 2; //2 columns wide

c.gridy = 2; //third row

pane.add(button, c);

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

c.fill = GridBagConstraints.HORIZONTAL;

c.ipady = 40; //make this component tall

c.weightx = 0.0;

c.gridwidth = 3;

c.gridx = 0;

c.gridy = 1;

pane.add(button, c);

Page 42: OOP 14 GUI DetailedReferenceSlides

Slide 42yewkh©2010

BoxLayoutimport java.awt.Component;

import java.awt.Container;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

public class BoxLayoutDemo {

public static void addComponentsToPane(Container pane) {

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

addAButton("Button 1", pane);

addAButton("Button 2", pane);

addAButton("Button 3", pane);

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

addAButton("5", pane);

}

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

JButton button = new JButton(text);

button.setAlignmentX(Component.CENTER_ALIGNMENT);

container.add(button);

}

private static void launchGUI() {

//Create and set up the window.

JFrame frame = new JFrame("BoxLayoutDemo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.

addComponentsToPane(frame.getContentPane());

//Display the window.

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

launchGUI();

}

}

The above code generates Box Layout arrangement of buttons. Run and study the code.

Page 43: OOP 14 GUI DetailedReferenceSlides

Slide 43yewkh©2010

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.

Page 44: OOP 14 GUI DetailedReferenceSlides

Slide 44yewkh©2010

Example

Create a Java technology GUI similar to above without the use of any layout manager.

Page 45: OOP 14 GUI DetailedReferenceSlides

Slide 45yewkh©2010

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

3. public class AddOneWidget_NullLayout{4. JFrame myFrame;5. Container myPane;6. JButton myButton;7. JPanel myPanel;8. 9. public AddOneWidget_NullLayout() {10. myFrame = new JFrame("Demo");11. myPane =

myFrame.getContentPane();12. myPanel = new JPanel();13. myButton = new JButton("Exit");14. }15. 16. public void createAndShowGUI(){17. myFrame.setLayout(null);18. myFrame.setSize(400,330); 19.

20. myPane.setBackground(Color.BLUE); 21. myPanel.setLayout(null);22. myPanel.setSize(300,200);23. myPanel.setLocation(50,50);24. myPanel.setBackground(Color.GREEN);25. 26. myButton.setSize(100,30);27. myButton.setLocation(100,85);28. myPane.add(myPanel);29. myPanel.add(myButton);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. } 38. }

Page 46: OOP 14 GUI DetailedReferenceSlides

Slide 46yewkh©2010

Good OOP practice

1. What we have done so far is to build the Java technology GUI in a single class.2. Below depicts the expected output and the corresponding UML describing the

design of the class.

3. The solution does not necessary has to be in a single 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.

Page 47: OOP 14 GUI DetailedReferenceSlides

Slide 47yewkh©2010

Good OOP practice

MyApp

-f: JFrame-pane: Container

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

MyGUI

-panel: Jpanel-button1: JButton

+MyGUI()+getPanel(): JPanel

<<Uses>>

Declare attributes for class.

Initiate components.Then assemble.Instantiate frame.

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

Return assembled panel and widgets.

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

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

Declare attributes for class.

Initiate components.

Assemble components.

Instantiate MyWindow and launch the program.

Page 48: OOP 14 GUI DetailedReferenceSlides

Slide 48yewkh©2010

1. import javax.swing.*;

2. public class MyGUI3. {4. JButton button1;5. JPanel panel;

6. public MyGUI()7. {8. button1 = new JButton(“Exit");9. panel = new JPanel();10. panel.add(button1);11. }

12. JPanel getPanel()13. {14. return panel; 15. }16. }

The GUI class

Declare attributes for class.

Initiate components.Then assemble.

Return assembled panel and widgets.

Page 49: OOP 14 GUI DetailedReferenceSlides

Slide 49yewkh©2010

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

3. public class MyApp4. {

5. public static void main(String[] args)6. {7. JFrame myFrame = new JFrame("Demo");8. Container myPane = myFrame.getContentPane();

9. MyGUI myGUIObject = new MyGUI();10. JPanel myPanel = myGUIObject.getPanel();11. myPane.add(myPanel);12. myFrame.pack();13. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);14. myFrame.setVisible(true);15. }16. }

The Application Class

Initialize JFrame object with parameter “Demo”.

Use JFrame method to retrieve the content pane.

Instantiate the other class MyGUI as object.

Call getPanel() method in MyGUI object

Resides in…

Resides in…

Page 50: OOP 14 GUI DetailedReferenceSlides

Slide 50yewkh©2010

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.

Page 51: OOP 14 GUI DetailedReferenceSlides

Slide 51yewkh©2010

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);

Show Message Dialog

Page 52: OOP 14 GUI DetailedReferenceSlides

Slide 52yewkh©2010

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]);

Show Option Dialog

Page 53: OOP 14 GUI DetailedReferenceSlides

Slide 53yewkh©2010

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

Show Confirm Dialog

Page 54: OOP 14 GUI DetailedReferenceSlides

Slide 54yewkh©2010

Show Input Dialog

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

Page 55: OOP 14 GUI DetailedReferenceSlides

Slide 55yewkh©2010

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!

Page 56: OOP 14 GUI DetailedReferenceSlides

Slide 56yewkh©2010

CLICK EVENT

JVM

Event Listening & Handling1. Event source automatically generates an event

when invoked.Examples:a. A button click or selecting a menu item

ActionEventb. A mouse click or movement

MouseEventc. A frame is closed or iconified

WindowEvent 2. Unfortunately, the components (both containers

and widgets) are unable to detect WHEN these events are invoked unless we do something…

3. We must add a listener (register event listener) to the GUI component.

4. How?

5. We also need to tell the GUI component how to respond if it hears the event. How?

Use addActionListener(…) method.

a. Create one or more handlers.b. Pass the handler as a parameter in

addActionListener(…) method. Example:

addActionListener(myEventHandler)

ActionListener

Take action!!!!Do something!!!

Page 57: OOP 14 GUI DetailedReferenceSlides

Slide 57yewkh©2010

Event Listening & Handling

JAVA

What should I listen to?

If I hear it, then what should I do?

JAVA

Oh.. I should listen to this button click

Then, I must immediately execute the handler.

Before the coding After the coding

Page 58: OOP 14 GUI DetailedReferenceSlides

Slide 58yewkh©2010

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 don’t 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?

Page 59: OOP 14 GUI DetailedReferenceSlides

Slide 59yewkh©2010

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){}

<<interface>>Interface01

+method01():void

MyClass+method01():void

<<interface>>ActionListener

+actionPerformed(ActionEvent event):void

MyClass+actionPerformed(ActionEvent event):void

Generic Interface Implementation

Implementing ActionListener inteface

Page 60: OOP 14 GUI DetailedReferenceSlides

Slide 60yewkh©2010

Event Handler

<<interface>>ActionListener

+actionPerformed(ActionEvent event):void

MyGUIClass+actionPerformed(ActionEvent event):void

<<interface>>ActionListener

+actionPerformed(ActionEvent event):void

MyActionHandler+actionPerformed(ActionEvent event):void

MyGUI+method1():void

<<uses>>

Two flavors of implementations:

•GUI and handler in the same class.

•GUI and handler in separate classes.

Page 61: OOP 14 GUI DetailedReferenceSlides

Slide 61yewkh©2010

Event Handling

(Image & content taken from Sun Microsystem SL275 –SE6

textbook)

There can be one or multiple handlers for

one single event.

Page 62: OOP 14 GUI DetailedReferenceSlides

Slide 62yewkh©2010

1. import javax.swing.*;2. import java.awt.*;3. import java.awt.event.*;

4. public class MyActiveGUI implements ActionListener {5. JButton button1;6. JPanel panel;

7. public MyActiveGUI() { 8. button1 = new JButton(“Exit”);9. button1.addActionListener(this);10. panel = new JPanel();11. panel.add(button1);12. }13. JPanel getPanel() { … }

14. public void actionPerformed(ActionEvent ae) {15. JButton but = (JButton) ae.getSource();16. String labelOnBut = but.getText();17. if (labelOnBut.equals(“Exit”)) {18. System.out.println(“Program terminated.");19. System.exit(1);20. }21. } 22. }

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.

This method you mustdefine when youimplements ActionListener

Refers to the current object. The current object is the handler because it implements the ActionListener.

Page 63: OOP 14 GUI DetailedReferenceSlides

Slide 63yewkh©2010

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

Adding Behavior to More than One Buttons

Page 64: OOP 14 GUI DetailedReferenceSlides

Slide 64yewkh©2010

Adding Behavior to More than One Buttons1. import javax.swing.*;2. import javax.swing.JOptionPane;3. import java.awt.*;4. import java.awt.event.*;

5. public class MultipleButtons implements ActionListener {

6. JFrame myFrame;7. Container myPane;8. JPanel myPanel;9. JButton loginButton;10. JButton clearButton;11. JButton exitButton;12. 13. public MultipleButtons(){14. myFrame = new JFrame("Event Handling

Demo");15. myPane = myFrame.getContentPane();16. myPanel = new JPanel();17. loginButton = new JButton("Login");18. loginButton.addActionListener(this);19. clearButton = new JButton("Clear");20. clearButton.addActionListener(this);21. exitButton = new JButton("Exit");22. exitButton.addActionListener(this);23. }

24. 25. public void createAndShowGUI(){26. myPanel.add(loginButton);27. myPanel.add(clearButton);28. myPanel.add(exitButton);29.

myPane.add(myPanel,BorderLayout.PAGE_END);30. myFrame.pack();31. myFrame.setVisible(true);32. }

33. public static void main(String [] args){34. MultipleButtons myDemo = new

MultipleButtons();35. myDemo.createAndShowGUI();36. }37. 38. public void actionPerformed(ActionEvent

ae){39. 40. JButton but = (JButton) ae.getSource();41. String labelOnBut = but.getText();

42. if (labelOnBut.equals("Login")) { 43. //perform login function44.

JOptionPane.showMessageDialog(myFrame,"Login successful");

45. }46. 47. if (labelOnBut.equals("Clear")) { 48. //perform textfield and password

field clearing function49.

JOptionPane.showMessageDialog(myFrame,"Please key in again.");

50. }51. 52. if (labelOnBut.equals("Exit")) { 53. int response =

JOptionPane.showConfirmDialog(myFrame, "Are you sure?", "Confirmation", JOptionPane.YES_NO_OPTION);

54. if (response==0)System.exit(0);55. } 56. }57. }

Page 65: OOP 14 GUI DetailedReferenceSlides

Slide 65yewkh©2010

getSource() method

1. Example:

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

2. 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.

3. Example:

(JButton) … cast the datatype to another type – JButton.

Page 66: OOP 14 GUI DetailedReferenceSlides

Slide 66yewkh©2010

Adding Behavior to Widget

1. public void actionPerformed(ActionEvent ae)2. {

3. Object comp = ae.getSource();

4. if (comp instanceof JButton)5. {6. JButton but = (JButton) comp;7. if (but == button1) {8. System.out.println("Entered: " +

textField.getText()); }9. }10. }

Page 67: OOP 14 GUI DetailedReferenceSlides

Slide 67yewkh©2010

Adding Multiple Behaviors to One Component1. We can add multiple behaviors to one component.

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

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)

Category Interface Methods to be implemented

Page 68: OOP 14 GUI DetailedReferenceSlides

Slide 68yewkh©2010

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

Adding Multiple Behaviors to One Component

Page 69: OOP 14 GUI DetailedReferenceSlides

Slide 69yewkh©2010

Adding Multiple Behaviors to One Component1. import javax.swing.*;

2. import java.awt.*;

3. import java.awt.event.*;

4. public class MultipleBehaviors implements MouseMotionListener, MouseListener {

5. private JFrame f;

6. private JTextField tf;

7. public MultipleBehaviors() {

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

9. tf = new JTextField(30);

10. }

11. public void launchFrame() {

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

13. f.add(label, BorderLayout.NORTH);

14. f.add(tf, BorderLayout.SOUTH);

15. f.addMouseMotionListener(this);

16. f.addMouseListener(this);

17. f.setSize(300, 200);

18. f.setVisible(true);

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. }

25. public void mouseEntered(MouseEvent e) {

26. String s = "The mouse entered";

27. tf.setText(s);

28. }

29. public void mouseExited(MouseEvent e) {

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

31. tf.setText(s);

32. }

33. // Unused MouseMotionListener method.

34. public void mouseMoved(MouseEvent e) { }

35. // Unused MouseListener methods.

36. public void mousePressed(MouseEvent e) { }

37. public void mouseClicked(MouseEvent e) { }

38. public void mouseReleased(MouseEvent e) { }

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

40. MultipleBehaviors two = new MultipleBehaviors();

41. two.launchFrame();

42. }

43. }

Page 70: OOP 14 GUI DetailedReferenceSlides

Slide 70yewkh©2010

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.

Summary of event listening and handling

Page 71: OOP 14 GUI DetailedReferenceSlides

Slide 71yewkh©2010

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.

Page 72: OOP 14 GUI DetailedReferenceSlides

Slide 72yewkh©2010

Multiple Windows

WindowMain.java

Window0.java Window1.java

Let’s walkthrough the UML and the Java code.

Page 73: OOP 14 GUI DetailedReferenceSlides

Slide 73yewkh©2010

Window0.java

Window0

-//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.

Declare fields for the widgets and containers.

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.

Page 74: OOP 14 GUI DetailedReferenceSlides

Slide 74yewkh©2010

Window0.java1. import javax.swing.*;2. import java.awt.*;3. import java.awt.event.*;4.5. public class Window06. {7. private JButton button0, button1;8. private JPanel panel;9. private JFrame frame;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. }

Create the frame object here (not in the main class!)

21. public void showFrame() {22. frame.setVisible(true);23. }24.25. public void hideFrame(){26. frame.setVisible(false);27. }28. }

Page 75: OOP 14 GUI DetailedReferenceSlides

Slide 75yewkh©2010

Window1.java

Window1

-//declare all the required WIDGET variables here-//declare all the required CONTAINER variables here

+Window1()+showFrame(): void+hideFrame(): void

Declare fields for the widgets and containers.

Pass “true” parameter to setVisible method.

Pass “false” parameter to setVisible method.

Instantiate the widget/container objects in the constructor.

Assemble them using add 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.

Page 76: OOP 14 GUI DetailedReferenceSlides

Slide 76yewkh©2010

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 panel;13. private JFrame frame;14.15. 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. }

25.26. public void showFrame(){27. frame.setVisible(true);28. }29.30. public void hideFrame(){31. frame.setVisible(false);32. }33. }

Pretty much the same as Window0.java

Page 77: OOP 14 GUI DetailedReferenceSlides

Slide 77yewkh©2010

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

Declare the fields for the two new windows that we are about to create.

WindowMain MUST add and define the method actionPerformed since it implements the ActionListener (an interface)

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.

Along with other widgets, instantiate the objects for both Window0 field and Window1 field.

This class object becomes an action listener by implementing ActionListener.

Study line by line the java code in WindowMain.java while referring to the above UML.

Page 78: OOP 14 GUI DetailedReferenceSlides

Slide 78yewkh©2010

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 panel;6. private JFrame frame;7. Window0 win1;8. Window1 win2;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);2021. win1 = new Window0("Window 1");22. win2 = new Window1("Window 2"); 23. }

WindowMain.java

Add Window0 and Window1 variables

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

Page 79: OOP 14 GUI DetailedReferenceSlides

Slide 79yewkh©2010

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. }36.37. public static void main(String args[]){38. WindowMain wm = new WindowMain("Main Window");39. wm.showFrame();40. }41. }

WindowMain.java

Event handling for both the buttons.

Page 80: OOP 14 GUI DetailedReferenceSlides

Slide 80yewkh©2010

Summary

1. The GUI packages in Java are in java.awt and javax.swing.2. There are different types of containers. A standalone application

has JFrame as its main container.3. Different container has different layout managers. Layout

managers determine how widgets are arranged in the container.4. Panel container can be used to display more than one widget.5. Commonly-used widgets are JButton, JTextField and JTextArea.6. Widgets and containers generate events, e.g.: keyboard presses,

mouse clicks, mouse motions, change of input values, etc.7. The purpose of “Event handling” is to determine how the

program should respond when an event is generated.

Page 81: OOP 14 GUI DetailedReferenceSlides

Slide 81yewkh©2010

Q & A

Page 82: OOP 14 GUI DetailedReferenceSlides

Slide 82yewkh©2010

Extra Reading

Read up javadoc on java.awt.Toolkit.