0% found this document useful (0 votes)
14 views55 pages

Event-Driven Programming in Java GUI

The document covers the fundamentals of event-driven programming and graphical user interfaces (GUIs) in Java, detailing key components such as JFrame, JButton, JTextField, and layout managers like FlowLayout and BorderLayout. It explains the differences between Java's AWT and Swing GUI packages, emphasizing the advantages of Swing for cross-platform compatibility. Additionally, it provides examples of GUI components, their usage, and how to implement them in Java applications.

Uploaded by

Redhu Malek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views55 pages

Event-Driven Programming in Java GUI

The document covers the fundamentals of event-driven programming and graphical user interfaces (GUIs) in Java, detailing key components such as JFrame, JButton, JTextField, and layout managers like FlowLayout and BorderLayout. It explains the differences between Java's AWT and Swing GUI packages, emphasizing the advantages of Swing for cross-platform compatibility. Additionally, it provides examples of GUI components, their usage, and how to implement them in Java applications.

Uploaded by

Redhu Malek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSC435 – OOP

Topic 07: EVENT-DRIVEN PROGRAMMING AND GRAPHIC


USER INTERFACE (GUI)
Content
2

 Introduction
 Graphical User Interface
 GUI Packages – AWT and Swing
 Basic Components – JButton, JTextField, JLabel, JFrame,
JPanel , JCheckBox, JRadioButton
 Event-driven Programming
 Events Handlers - events listeners and events source
 Layout manager – FlowLayout, BorderLayout, GridLayout

Mohd Hanapi Abdul Latif


Graphical User Interface (GUI)
3

 Using such graphical component called widgets referred to


as WIMP GUI where W=windows, I=icons, M=menus,
P=pointers.
 Basic components are :- Windows, Icons, Menu, Text, Push
button, Toggle buttons, Radio buttons, Combo boxes, Sliders
 Graphics programming in JAVA is clearly component
oriented.
 Screen images are assembled by adding various components
to an instance of the container class.

Mohd Hanapi Abdul Latif


GUI
4

 A user interacts with the application by :


 Clicking on a button
 Making a choice from a menu

 Entering text in a text field

 Dragging a scroll bar

Mohd Hanapi Abdul Latif


GUI
5

 Two types of window in GUI programs:


 Dialog

 Frame

 A dialog is a limited-purpose window used primarily for


displaying simple information such as an error messages or
getting a simple response.
 A frame is a general-purpose window in which the user interacts
with the application. Windows in which the user writes a
document, draws a picture, sends e-mail, and so on are all frames.
 A Java GUI application program must have at least one frame
that serves as the program’s main window.

Mohd Hanapi Abdul Latif


GUI
6

 JAVA has two GUI packages


1. Abstract Window Toolkit (AWT) - [Link].*
◼ Implemented by using the native GUI objects and depends on the operating
system.
◼ Offers a set of OO classes for quickly developing GUIs and handling events.
◼ Many components rely on heavyweight components

2. Swing ([Link].*)
◼ Provide greater compatibility across different operating systems.
◼ Implemented fully in Java and behave the same on different operating
system
◼ It is called “lightweight class”
◼ You should prefer using Swing because of its use of lightweight components
◼ Support many new functionalities.
◼ Components normally have prefix J to distinguish from AWT component

Mohd Hanapi Abdul Latif


[Link]
7

 Swing GUI components names start with J.


 [Link] → [Link]
 [Link] → [Link]

 [Link] → [Link]

 However, there are additional classes, such as,


[Link] has no corresponding AWT
component

Mohd Hanapi Abdul Latif


Classes in the GUI
Hierarchy
8

Mohd Hanapi Abdul Latif


Sample of GUI objects
9

 Various GUI objects from the [Link] package.

Mohd Hanapi Abdul Latif


JOptionPane
10

 Using the JOptionPane class is a simple way to display the


result of a computation to the user or receive an input from
the user.
 We use the showMessageDialog class method for output.
 We use the showInputDialog class method for input. This
method returns the input as a String value so we need to
perform type conversion for input of other data types

Mohd Hanapi Abdul Latif


Using JOptionPane for Output
11

import [Link].*;
. . .

[Link]( null, “I Love Java” );

Mohd Hanapi Abdul Latif


JOptionPane for Input
12

import [Link].*;
. . .

String inputstr =

[Link]( null, “What is your name?” );

Mohd Hanapi Abdul Latif


Subclassing JFrame
13

 To create a customized frame window, we define a subclass


of the JFrame class.

 The JFrame class contains rudimentary functionalities to


support features found in any frame window.

Mohd Hanapi Abdul Latif


Creating a Plain JFrame
14

import [Link].*;
class DefaultJFrame {
public static void main( String[] args ) {
JFrame defaultJFrame;
defaultJFrame = new JFrame();
[Link](true);
}
}

Mohd Hanapi Abdul Latif


JFrame
15

 Create a JFrame so that you can place objects within it for


display.
 Has four constructors :
1. JFrame()
- constructs a new frame that is initially invisible and no title
2. JFrame(String title)
- creates a new, initially is invisible frame with specified title.

3. JFrame(GraphicsConfiguration gc)
– creates a frame in the specified GraphicsConfiguration of a screen device
and a blank title.
4. JFrame(String title, GraphicsConfiguration gc)
– creates a frame with the specified title and the specified
GraphicsConfiguration of a screen.

Mohd Hanapi Abdul Latif


Some JFrame Method
16

 void setTitle(String title) – set title of the frame


 void setSize(int x, int y) – set size of the frame
 void setLocation(int x, int y) – set location of the frame
 Container getContentPane()
 Returns the contentPaneobject for this frame.
 void setDefaultCloseOperation(int operation)
 Sets the operation that will happen by default when the user initiates a
“close”on this frame.
 You must specify one of the following choices:
◼ WindowsConstants.DO_NOTHING_ON_CLOSE
◼ WindowsConstants.HIDE_ON_CLOSE
◼ WindowsConstants.DISPOSE_ON_CLOSE
◼ JFrame.EXIT_ON_CLOSE
 void setLayout(LayoutManager manager)
 By default the layout of this component may not be set, the layout of its
contentPane should be set instead.
Mohd Hanapi Abdul Latif
Example of JFrame
import [Link].*;
public class testFrame
{
public static void main(String[] args)
{
JFrame f = new Jframe("First Frame");
[Link](200, 100);
Creating a Subclass of JFrame
[Link](true);
} import [Link].*;
} public class testFrame1 extends JFrame
{
public testFrame1()
{
setTitle("My First Subclass");
setSize(300, 200);
setLocation(250, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args)


{
testFrame1 f1 = new testFrame1();
[Link](true);
}
}
17
CONTAINER - Content pane
18

 A frame’s content pane is an area of the frame that is used


to display the content such as text, image, etc. Exclude the
title and menu bars and the border.
 Access the content pane of a frame by calling the frame’s
getContentPane method

Mohd Hanapi Abdul Latif


Example of Content Pane
19

import [Link].*;
import [Link].*; This blue
public class testFrame2 extends JFrame { area is the
content pane
public testFrame2() {
of this frame.
setTitle("My Extend Frame");
setSize(300, 200);
setLocation(250, 150);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Container c = getContentPane(); cause program to stop when the


[Link]([Link]); frame is closed (click on X)
}

public static void main(String[] args) {


testFrame2 f = new testFrame2();
[Link](true);
}
}

Mohd Hanapi Abdul Latif


Common GUI components
20

Component Description

JLabel An area where uneditable text or icons can be displayed

JTextField An area in which the user inputs data from the keyboard. The area can
also display information
JButton An area that triggers an event when clicked

JCheckBox A GUI component that is either selected or not selected

JComboBox A drop-down list of items from which the user can make a selection by
clicking an item in the list or by typing into the box, if permitted
JList An area where a list of items is displayed from which the user can
make a selection by clicking once on any element in the list. Double-
clicking an element in the list generates an action event. Multiple
elements can be selected.
JPanel A container in which components can be placed

JRadioButton A GUI component that has on/off or true/false values


Mohd Hanapi Abdul Latif
Example GUI Components :
21

Mohd Hanapi Abdul Latif


JLabel
22

 Used to create an area where uneditable text or icons can be


displayed.
 JLabel constructors
 JLabel()
◼ Creates a Jlabel instance with no image and with an empty string for the title.
 JLabel(Iconimage)
◼ Creates a Jlabel instance with the specified image.
 JLabel(Iconimage, int horizontalAlignment)
◼ Creates a Jlabel instance with the specified image and horizontal alignment.
 JLabel(String text)
◼ Creates a Jlabel instance with the specified text
 JLabel(String text, Iconicon, int horizontalAlignment)
◼ Creates a Jlabel instance with the specified text, image, and horizontal alignment.
 JLabel(String text, int horizontalAlignment)
◼ Creates a Jlabel instance with the specified text and horizontal alignment h

Mohd Hanapi Abdul Latif


JLabel example
23

 To create the label or text

JLabel lbl = new JLabel("Other Color");

JLabel rmlbl = new JLabel("RM");

Mohd Hanapi Abdul Latif


JTextField
24

 The area used to input or display data

JTextField txtcolor = new JTextFied(10);

JTextField txtrm = new JTextFied(5);

JPasswordField: show inputted text as *

JPasswordField = new JPasswordField(10);

Mohd Hanapi Abdul Latif


JButton
25

 Command button where the user click and the event will
occur

JButton calcbut = new JButton("Calculate");


JButton resetbut = new JButton("Reset");
JButton exitbut = new JButton("Exit");

Mohd Hanapi Abdul Latif


JRadioButton
26

 A GUI component that has on/off or true/false values


 User only click one option out of a list of options.
 Each option must be created using JRadioButton
JRadioButton JRIswara = new JRadioButton("Proton Iswara");
JRadioButton JRGen2 = new JRadioButton("Proton Gen2");
JRadioButton JRWaja = new JRadioButton("Proton Waja");

⚫ Once all the options created, you need to group it together so only
one option can be chosen by user, if not all the options can be
selected.
ButtonGroup modelgrp = new ButtonGroup();
[Link](JRIswara);
[Link](JRGen2);
[Link](JRWaja);

Mohd Hanapi Abdul Latif


JCheckBox
27

 A GUI component that is either selected or not selected


 User can select multiple options from the list

JCheckBox CBSpoiler = new JCheckBox("Spoiler");


JCheckBox CBRim = new JCheckBox("Sports Rim");
JCheckBox CBLight = new JCheckBox("Sports Light");
JCheckBox CBHood = new JCheckBox("Hood");

Mohd Hanapi Abdul Latif


Layout Managers
28

 To adjust the GUI objects within their container(frame, dialog,


applet, etc) is resized.
 There are 3 different types of layout manager
 FlowLayout
 BorderLayout

 GridLayout

Mohd Hanapi Abdul Latif


FlowLayout
29

 In this layout, GUI components are placed in left-to-right order.


 When the component does not fit on the same line, left-to-right placement
continues on the next line.
 Default, components on each line are centered.
 When the frame is resized, the containing component is resized and the
placement of component is adjusted accordingly.
Container contentPane = getContentPane();
[Link](new FlowLayout);
 Sample of FlowLayout screen

For coding, please refer to File:


[Link]

Mohd Hanapi Abdul Latif


BorderLayout
30

 Divides the container into five regions : Center, North, South, East
and West
Container contentPane = getContentPane();
[Link](new BorderLayout());
……………
[Link](butt1, [Link]);
[Link](butt2 [Link]);
[Link](butt3, [Link]);
[Link](butt4, [Link]);
[Link](butt5, [Link]);
 Sample of BorderLayout screen

For coding, please refer to File:


[Link]

Mohd Hanapi Abdul Latif


GridLayout
31

 Places GUI components on equal size R x C grids.


 Components are placed in top-to-bottom, left-to-right order.
 The number of columns is irrelevant, the layout will create the
number of rows and adjust the number of columns accordingly to
fit all the components.
 Similar to FlowLayout
Container contentPane = getContentPane();
[Link](new GridLayout(r, c)); //r = number of rows
//c = number of columns
 Sample of GridLayout screen
For coding, please refer to File:
[Link]

Mohd Hanapi Abdul Latif


PANELS
32

 Requires each component be placed in an exact location.


 Often consists of multiple panels with each panel’s components
arranged in a specific layout.
 Panels are created with class JPanel – a subclass of JComponent
inherits from class Container.
 Every JPanel is a Container.
 JPanel may have components, including other panels added to
them.

Mohd Hanapi Abdul Latif


JPanel
33

 Is a Swing component that provides a screen area used for


creating GUI components.
 Can separate different regions, placing a JPanel object into each
region.
 Use multiple panels, placing panels inside other panels – nested
panels.
 Example :

JButton okbut = new JButton("OK"); //create button OK


JPanel inPnl = new JPanel(new GridLayout(3,1));
[Link](okbut); //add the button onto the panel created

Mohd Hanapi Abdul Latif


Example: Combine the grid layout, border
layout in the JPanel
34

Mohd Hanapi Abdul Latif


Combine the grid layout, border layout in the JPanel

layout = new BorderLayout(); OutPnl = new JPanel(new FlowLayout());


cont = getContentPane(); lblans = new JLabel("Total Interest : RM");
ans = new JTextField(5);
[Link](layout); [Link](lblans);
[Link](ans);
InpPnl = new JPanel(new GridLayout(3,1));
lblloan = new JLabel("Loan Amount");
btnReset = new JButton("Clear");
loan = new JTextField(5); btnCalc = new JButton("Compute");
lblrate = new JLabel("Interest Rate"); btnExit = new JButton("Exit");
rate = new JTextField(5); pnlButton = new JPanel(new FlowLayout());
lblperiod = new JLabel("Loan Period "); [Link](btnReset);
[Link](btnCalc);
period = new JTextField(5); [Link](btnExit);
[Link](lblloan);
[Link](loan); [Link](this);
[Link](lblrate); [Link](this);
[Link](this);
[Link](rate);
[Link](InpPnl, [Link]);
[Link](lblperiod); [Link](OutPnl, [Link]);
[Link](period); [Link](pnlButton, [Link]);

Complete Program – Download [Link]


Event-driven programming
36

 An event occurs when the user interacts with a GUI object.


 In event-driven programs, objects respond to the event by
defining event-handling methods.

Mohd Hanapi Abdul Latif


Main concept
37

 Graphical components code


 That makes up the Graphical User Interface
 Listener code
 That receives the events and respond to them
 Application code
 That do useful work for the user

Mohd Hanapi Abdul Latif


JAVA Interface
38

 A JAVA interface specifies a behavior of a GUI component


created.
 JAVA package [Link] contains many interfaces that are
designed for ‘listening’ for events that occur in a program
 An event can be a button press, selecting item from combo box,
radio buttons or check box selected.
 When event occurs, the event is received and handled by a ‘JAVA
listener’ – are provided as interfaces.
 Function of listener interfaces are to ‘listen for’ or be aware when
an event occurs and to provide the necessary program control to
perform the required task.

Mohd Hanapi Abdul Latif


Event Handling
39

 GUI is a asynchronous program – events occur in the


program at unpredictable times.
 It is referred to as an event-driven program – it waits for
input from the user before performing a task.
 Event-model = takes the user’s interaction with the GUI
control such as mouse click

Mohd Hanapi Abdul Latif


Container as Event Listener
40

 Instead of defining a separate event listener such as


ButtonHandler, much more common to have an object that contains
the event sources be a listener.
 Example : a frame as a listener of the action events of the
buttons.

Mohd Hanapi Abdul Latif


Event Handling
41

Mohd Hanapi Abdul Latif


Event Source and Event Listener
42

A listener must be registered to a event source. Once


registered, it will get notified when the event source
generates events.

Mohd Hanapi Abdul Latif


Event Types
43

 Registration and notification are specific to event types


 Mouse listener handles mouse events
 Item listener handles item selection events
 The most common events is the action event such as clicking on a
button, selection a menu item.
 Action events are generated by action event sources and handled
by action event listeners

Mohd Hanapi Abdul Latif


Handling Action Events
44

Example:
JButton button = new JButton("OK");
ButtonHandler handler = new ButtonHandler( );

[Link](handler);

Mohd Hanapi Abdul Latif


ActionListener Interface
45

 We need to call addActionListener method to handler the


event source, we need a class that implements the
ActionListener Interface.
 The ActionListener interface includes one method named
actionPerformed.
 A class that implements the ActionListener interface must have
a method named actionPerformed – this method contains all
the codes to be executed in response to the events (for each
GUI components created)

Mohd Hanapi Abdul Latif


User Interface Actions and Listener Interfaces
46

Mohd Hanapi Abdul Latif


AWT and Swing Listener Interfaces
47

Mohd Hanapi Abdul Latif


Example
48

If OK button
is pressed

If CANCEL
button is
pressed

Mohd Hanapi Abdul Latif


import [Link].*;
import [Link].*;
import [Link].*;
public class testFrame extends JFrame implements
ActionListener
{ //Create the TextField component to input the data and place
private JLabel title; on the container
private JTextField text; text = new JTextField(20);
private JButton cancel, ok; [Link](text);

public testFrame() //Create the Command Buttons and place on the container
{ ok = new JButton("OK");
//Set the Frame properties cancel = new JButton("CANCEL");
setTitle("Testing Frame with Label and Buttons"); [Link](ok);
setSize(300, 200); [Link](cancel);
setLocation(150, 250);
//Register the frame as an action listener of the events -
//Create the Container and set the Layout Manager textfield and buttons
Container cont = getContentPane(); [Link](this);
[Link](new FlowLayout()); [Link](this);
[Link](this);
//Create the Label component and place on the }
container
title = new JLabel("Please Enter Your name");
[Link](150, 25);
[Link](title);
public void actionPerformed(ActionEvent e)
{
if([Link]() == ok)
{
String name = [Link]();
[Link]("You have entered My Name is " + name);
}
else
if([Link]() == cancel)
{
[Link](" ");
[Link]("You have cancelled the operation");
}
}
public static void main(String[] args)
{
//Create a Frame object and make it visible to be used,
//and close all operation upon exit
testFrame f = new testFrame();
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}
Other Common GUI Components
51

 JCheckBox
 see [Link] and [Link] -
page 840 & 842
 JRadioButton
 see [Link] - page 845
 JComboBox
 see [Link] - page 845
 JList
 see [Link] - page 852
 JSlider
 see [Link] - page 855

Mohd Hanapi Abdul Latif


Menus
52

 The [Link] package contains three menu-related classes:


JMenuBar, JMenu, and JMenuItem.
 JMenuBar is a bar where the menus are placed. There is one
menu bar per frame.
 JMenu (such as File or Edit) is a group of menu choices. JMenuBar
may include many JMenu objects.
 JMenuItem (such as Copy, Cut, or Paste) is an individual menu
choice in a JMenu object.
 Only the JMenuItem objects generate events.

Mohd Hanapi Abdul Latif


Menu Components
53

Edit View Help

JMenuBar File Edit View Help

JMenu
JMenuItem

separator

Mohd Hanapi Abdul Latif


Sequence for Creating Menus
54

1. Create a JMenuBar object and attach it to a frame.


2. Create a JMenu object.
3. Create JMenuItem objects and add them to the JMenu
object.
4. Attach the JMenu object to the JMenuBar object.

Mohd Hanapi Abdul Latif


Use GUI Builder
55

 As you seen, implementing a simple GUI in Java is quite tedious.


 You have to write a lot of code for constructing component.
 GUI builder help you to implement GUI in 3 ways:
 Drag and drop onto a panel. The GUI builder write the layout management
code for you
 Customize components with dialog box, setting properties. The GUI builder
write the customization code for you.
 You provide event handler by picking the event to process and providing just
the code snippet for the listener method. The GUI builder write the
boilerplate code for attaching a listener object
 The free GUI builder (NetBeans) available from [Link]
 [Link]

Mohd Hanapi Abdul Latif

You might also like