You are on page 1of 32

Lecture 09

Chapter 7
Graphical User Interface(GUI) and
Event Driven Programming
By: Mequanent Argaw
Debre Markos University

12/31/2015 Department of ECE, College of Technology 1


Graphical User Interface Programming

A graphical user interface (GUI) presents a user-friendly

mechanism for interacting with an application.

Why we learn about GUI?


 You might build applications that other people are going to use.

 You might need to build applications that require a graphical interface.

 Command-line and Console applications are weak, inflexible and

unfriendly.

 GUI(Goo-ee) gives an application a distinctive “look and feel.”

12/31/2015 Department of ECE, College of Technology 2


How GUI is achieved in Java
Two ways to create a GUI in Java

1. Abstract Window ToolKit : in java.awt package


 These are GUI classes in the early days of java ( JDK 1.0 and 1.1).

 Look like the native GUI components of the platform on which a java program executes.

 Heavyweight components – they rely on the local platform’s OS to determine their functionality and

their look and feel.

2. Swing: in javax.swing package


 Newer GUI library that allows a powerful graphics and GUI construction(JDK 1.2+).

 Most GUI components are Lightweight components- they are written, manipulated and displayed

completely in Java.

 Benefits: rich features, compatible, and supports OO design.

12/31/2015 Department of ECE, College of Technology 3


GUI Terminology
Window: A first-class citizen of the graphical desktop.
 Also called a top-level container.
 examples: frame, dialog box
 Component: A GUI widget that resides in a window.
 Also called controls.
 examples: button, text box, label

 Container: A logical grouping for storing components.


 Examples: Panel, box

12/31/2015 Department of ECE, College of Technology 4


Components

12/31/2015 Department of ECE, College of Technology 5


Swing Inheritance Hierarchy (1/2)
Class Component (java.awt) declares common features of GUI
components in package java.awt and javax.swing.
A Container object (java.awt) can be used to organize components by
attaching the components to the container.
Class JComponent( javax.swing) is the superclass of all lightweight
swing components and declares their common attributes and behaviors.

12/31/2015 Department of ECE, College of Technology 6


Swing Inheritance Hierarchy (2/2)
Component (AWT)
import java.awt.*;
 Window
import javax.swing.*;
 JFrame (Swing)

 JDialog

Container
 JComponent (Swing)
 JButton JColorChooser JFileChooser JPanel

 JComboBox JLabel JList JScrollbar

 JMenuBar JOptionPane JSpinner JTable

 JPopupMenu JProgressBar JTextArea JTree

 JScrollPane Jslider JTabbedPane JToolbar

 JSplitPane JTextField ...Department of ECE, College of Technology


12/31/2015 7
JFrame
a graphical window to hold other components

Constructors:
 public JFrame()

 public JFrame(String title)


 Creates a frame with an optional title.

 Call setVisible(true) to make a frame appear on the screen after creating it.

 public void add(Component comp) places the given component or


container inside the frame.

12/31/2015 Department of ECE, College of Technology 8


More JFrame
public void setDefaultCloseOperation(int op) makes the
frame perform the given action when it closes.
 common value passed: JFrame.EXIT_ON_CLOSE

 if this is not set, the program will never exit even if the frame is closed.

public void setSize(int width, int height)

Gives the frame a fixed size in pixels.

public void pack()

Resizes the frame to fit the components inside it.

12/31/2015 Department of ECE, College of Technology 9


JButton
a clickable region for causing actions to occur

 public JButton(String text)


Creates a new button with the given string as its text.

 public String getText()

Returns the text showing on the button.

 public void setText(String text)

Sets button's text to be the given string.

12/31/2015 Department of ECE, College of Technology 10


Demo: GUI Example
import javax.swing.*;

import java.awt.*;

public class SimpleGUI{


public static void main(String[] args){
JFrame frame = new JFrame();
JButton btn = new JButton(“Click Me”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(btn);
frame.setSize(300,300);
frame.setVisible(true);

}
12/31/2015 Department of ECE, College of Technology 11
Containers and Layout
Place components in a container; add the container to a frame.
 container: An object that stores components and governs their positions,
sizes, and resizing behavior.

12/31/2015 Department of ECE, College of Technology 12


JFrame as container
A JFrame is a container. Containers have the following methods:

public void add(Component comp)

public void add(Component comp, Object info) adds a component to

the container, possibly giving extra information about where to place it.

public void remove(Component comp)

public void setLayout(LayoutManager mgr)

Uses the given layout manager to position components.

12/31/2015 Department of ECE, College of Technology 13


GUI Layout: Sizing and Positioning
1. FlowLayout

public FlowLayout()

treats container as a left-to-right, top-to-bottom "paragraph".


 Components are given preferred size, horizontally and vertically.

 Components are positioned in the order added.

 If too long, components wrap around to the next line.

myFrame.setLayout(new FlowLayout());

myFrame.add(new JButton("Button 1"));

 The default layout for containers other than JFrame.

12/31/2015 Department of ECE, College of Technology 14


2. BorderLayout
public BorderLayout()
Divides container into five regions:

NORTH and SOUTH regions expand to

fill region horizontally, and use the

component's preferred size vertically.

WEST and EAST regions expand to fill region

vertically, and use the component's preferred size horizontally.

CENTER uses all space not occupied by others.

myFrame.setLayout(new BorderLayout());

myFrame.add(new JButton("Button 1"),

BorderLayout.NORTH);

This is the default layout for a JFrame.


12/31/2015 Department of ECE, College of Technology 15
3. GridLayout
Public GridLayout(int rows, int columns)
 Treats container as a grid of equally-sized rows and columns.
 Components are given equal horizontal / vertical size,
disregarding preferred size.
 Can specify 0 rows or columns to indicate expansion in that
direction as needed.

12/31/2015 Department of ECE, College of Technology 16


4. BoxLayout
Is similar to FlowLayout in that each component gets its own
size and the components are placed in the order in which
they are added.
However a BoxLayoutManager can stack the components
vertically(usually) or horizontally.
Unlike FlowLayout instead of having automatic ‘component
wrapping’ you can insert a sort of ‘component return key’ and
force the components to start on a new line.

12/31/2015 Department of ECE, College of Technology 17


Interacting with a GUI Component
 A graphical user interface (GUI) has two aspects “Look and Feel”.

 Look is the appearance of our GUI components and programs.

 Feel refers to the interaction between the GUI and the USER.
How does one interact with GUI ?
The question is “ How to get the button to do something specific when a user clicks it? ”

We need two things:


 A method to be called when the user clicks( the thing you want to happen as a result of the button

click).

 A way to know when to trigger that method. In other words a way to know when the user clicks

the button!

12/31/2015 Department of ECE, College of Technology 18


Capturing a user event
Suppose we want the text on the button to change from “Click Me” to “I have been

clicked” when the user presses the button.

Step 1: Write a method that changes the text of the button.

public void changeText(){

button.setText(“I have been clicked”);

Step 2 : Determine when the button is clicked (but How?)

In Java, the process of getting and handling a user event is called event-handling.

A user pressing a button is an EVENT.

12/31/2015 Department of ECE, College of Technology 19


Capturing a user event …
 To capture and handle a user event we need to
perform or carry out two specific tasks:
1. We need to tell the button that we are interested about
the actions that happen on it.

2. The button needs a way to let us know when an action


happens on it (like when a user clicks the button).

12/31/2015 Department of ECE, College of Technology 20


Listener Interface
If you want to tell the button that you are interested about the

actions(EVENTS) that happen on it, implement an interface that says, “I

am listening for your events.” – in other words implement a Listening

Interface.

Swing GUI Components ( like a button) are event sources.

An event source is an object that can turn user actions into objects called

events (e.g. MouseEvent, KeyEvent, WindowEvent, ActionEvent…)

An event source creates an event object when the user performs some

action on it.

You will act as a listener receiving events rather than creating events.
12/31/2015 Department of ECE, College of Technology 21
Listener Interface…
Every event type has a matching listener interface.

For example if you want to receive MouseEvents


you should implement MouseListener interface.

To implement an interface:


 You should declare that you implement it, which
means

 You must write implementation methods for every


method in that interface.

12/31/2015 Department of ECE, College of Technology 22


Communication between listener and source
The Listener

If you want to know about a button’s action event


 Implement the ActionListener Interface.

 To tell the button you are interested, you register with the button by calling its

addActionListener(this) method and since you are the ActionListener you pass

your class(this) as an ActionListener reference.

The button needs a way to call you back when the event happens:
 So it calls the method in the ActionListener interface.

 As an ActionListner, you must implement the interface’s method,

actionPerformed().
12/31/2015 Department of ECE, College of Technology 23
Getting a button’s Action Event
1. Implement the ActionListener Interface.

2. Register with the button( tell it you want to


listen for events).

3. Define the event-handling


method( implement the actionPerformed()
method from the ActionListener interface).
12/31/2015 Department of ECE, College of Technology 24
Communication between listener and source…
The Event Source

A button is a source of Action Events, so it has to know which

objects are interested listeners.

The button has an addActionListener( ) method to give interested

objects(listeners) a way to tell the button they are interested.

When the addActionListener( ) method is called the button takes

the parameter( a listener object) and stores it in a list.

When a user clicks the button, the button ‘fires’ the event by calling

the actionPerformed() method on each listener in the list.


12/31/2015 Department of ECE, College of Technology 25
Demo: Interacting with a JButton
import javax.swing.*;
import java.awt.event.*;
public class SimpleGUI2 implements ActionListener{
JButton button;
public static void main(String[] args){
JFrame frame = new JFrame(“Frame 1”);
button = new JButton(“Click Me”);
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
button.setText(“I have been clicked!”);
}
}
12/31/2015 Department of ECE, College of Technology 26
Summary: Graphical events
 event: An object that represents a user's interaction with a GUI component;

can be "handled" to create interactive components.

 listener: An object that waits for events and responds to them.


 To handle an event, attach a listener to a component.

 The listener will be notified when the event occurs (e.g. button click).

12/31/2015 Department of ECE, College of Technology 27


Summary: Event-driven Programming
Event-driven programming: A style of coding where a program's

overall flow of execution is dictated by events.


 Rather than a central "main" method that drives execution, the program loads

and waits for user input events.

 As each event occurs, the program runs particular code to respond.

 The overall flow of what code is executed is determined by the series of events

that occur, not a pre-determined order.

12/31/2015 Department of ECE, College of Technology 28


Summary: Event hierarchy
importjava.awt.event.*;

EventObject  EventListener
 AWTEvent (AWT)  AWTEventListener
 ActionEvent  ActionListener
 TextEvent  TextListener
 ComponentEvent  ComponentListener
 FocusEvent  FocusListener
 WindowEvent  WindowListener
 KeyEvent  KeyListener
 MouseListener
 MouseEvent

12/31/2015 Department of ECE, College of Technology 29


Summary: Action events
 Action event: An action that has occurred on a GUI
component.
 The most common, general event type in Swing. Caused by:
 button or menu clicks,

 Check box checking / unchecking,

 pressing Enter in a text field, ...

 Represented by a class named ActionEvent

 Handled by objects that implement interface ActionListener

12/31/2015 Department of ECE, College of Technology 30


Summary: Implementing a listener
public class name implements ActionListener {
public void actionPerformed(ActionEvent event) {

//code to handle the event;

 JButton and other graphical components have this method:

 public void addActionListener(ActionListener al)

Attaches the given listener to be notified of clicks and events that occur on

this component.
12/31/2015 Department of ECE, College of Technology 31
Exercise
 Write a simple calculator Graphical Interface using GUI
Programming.

12/31/2015 Department of ECE, College of Technology 32

You might also like