STIA1123 : Programming 2
GUI (Part 2)
OBJECTIVES
▶ Understand & differentiate the various objects involved in the event
handling for GUI components.
▶ Implement application GUI event handling using Netbeans Swing Gui
Builder Tool
EVENT-DRIVEN PROGRAMMING
▶ In event-driven programming, code is executed upon
activation of events.
▶ Ex: a button click, or mouse movement
3
EVENT AND EVENT SOURCE OBJECT
▶ An event can be defined as a type of signal to the
program that something has happened.
▶ The event object is generated by external user actions
such as mouse movements, mouse button clicks, and
keystrokes, or by the operating system, such as a timer.
▶ The component on which an event is generated is called
the source object.
▶ Ex: source object: Button for a button-clicking action event.
4
EVENT CLASSES
Subclasses an event is an object of the EventObject
class
EVENT INFORMATION
▶ An event object contains whatever properties are pertinent
to the event.
▶ You can identify the source object of the event using the
getSource() instance method in the EventObject class.
▶ The subclasses of EventObject deal with special types of
events, such as button actions, window events, component
events, mouse movements, and keystrokes.
6
SELECTED USER ACTIONS
Source Event Object Type
User Action Object Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press Enter on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Select item(s) JList ListSelectionEvent
Select a menu item JMenuItem ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
7
LISTENERS, REGISTRATIONS,
AND HANDLING EVENTS
▶ Java uses a delegation-based model for event handling
▶ An external user action on a source object triggers an event
object
▶ An object interested in the event receives the event
▶ This latter object is called a listener object
8
LISTENERS, REGISTRATIONS,
AND HANDLING EVENTS
▶ Two things are needed for an object to be a listener for an event on
a source object:
1. The listener object’s class must implement the corresponding event-
listener interface & override the corresponding listener method. Java
provides a listener interface for every type of GUI event.
The listener interface is usually named XListener for XEvent ,
Ex: Listener interface for ActionEvent is ActionListener
each listener for ActionEvent should implement the ActionListener
interface & override the listener’s method named
actionPerformed(ActionEvent)
9
SELECTED EVENT HANDLERS
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent) MouseEvent
MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
10
LISTENERS, REGISTRATIONS,
AND HANDLING EVENTS
▶ Two things are needed for an object to be a listener for an event on
a source object:
2. The listener object must be registered by the source object. Registration
methods are dependent on the event type
Ex: For ActionEvent, the method is addActionListener
In general: the method is named addXListener for XEvent
11
LISTENERS, REGISTRATIONS,
AND HANDLING EVENTS
▶ For each event, the source object maintains a list of listeners and
notifies all the registered listeners by invoking the handler on the
listener object to respond to the event.
12
THE DELEGATION MODEL: EXAMPLE
ListenerClass listener = new ListenerClass();
JButton okBtn = new JButton("OK");
[Link](listener);
class ListenerClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
S.o.p (“Button “+ [Link]()+ “ is
clicked.”);} 13
GUI EVENT HANDLING USING
NETBEANS GUI BUILDER TOOL
▶ Here we will add the event handling for the GUI that we have built
previously
▶ The GUI is shown again below
▶ Specifically, we’ll add the functionality for the two buttons, Compute &
Reset
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
1. Renaming the GUI components variables
The reference variables for GUI objects (such as buttons & textfields)
should be renamed so that we can easily identify them in the
codes generated by Netbeans GUI Builder
• Right-click the Compute button and select Change Variable Name…
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
1. Renaming the GUI components variables
• In the Rename dialog box, type ‘computeBtn’. (The variable name for
the Compute button has been changed from jButton1 to computeBtn)
• Repeat the previous steps to rename the variable for Reset button from
jButton2 to resetBtn
resetBtn
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
1. Renaming the GUI components variables
• Next we are going to rename all the variables for the four textfields
• Right-click the textfield beside label ‘Length:’ and select Change
Variable Name…
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
1. Renaming the GUI components variables
• In the Rename dialog box, type ‘lengthTF’. (The variable name for the
Length textfield has been changed from jTextField1 to lengthTF)
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
1. Renaming the GUI components variables
• Repeat the previous steps to rename the remaining three textfields:
- the variable for Width textfield from jTextField2 to widthTF
- the variable for Area textfield from jTextField3 to areaTF
- the variable for Perimeter textfield from jTextField4 to perimeterTF
widthTF
areaTF
perimeterTF
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
Making the Compute Button Work
First, we will make the Compute button works by assigning the
handler to the button:
Specifically, we will use ActionListener responding to
ActionEvent
•Right Click on the Compute button. From the pop-up menu choose Events -->
Action --> actionPerformed.
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
• Netbeans will automatically add an ActionListener to the Compute button
and generate a handler method for handling the listener's actionPerformed
method
• You will be brought into the Source Code window where you implement the
action you want the Compute button to do when the button is pressed. Your
Source Code window should contain the following lines which is the
actionPerformed method that you need to override:
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
• Next, we add the codes to implement what we want the Compute Button to
do (replacing the // TODO add your handling code here: line)
• The action performed by the Compute button can be divided into 3 steps:
1. It is going to accept user inputs, length & width, from the textfields
lengthTF and widthTF and convert the inputs from type String to
double,
2. It will then perform calculation of rectangle area & perimeter based on
the inputs length & width,
3. It will convert the area & perimeter to type String and place them in
the areaTF & perimeterTF respectively.
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
• The finished source code shall look like this:
Step 1
Step 2
Step 3
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
Making the Reset Button Work
Next, we will make the Reset button works by assigning the
handler to the button:
Again, we will use ActionListener responding to ActionEvent
•Right Click on the Reset button. From the pop-up menu choose Events -->
Action --> actionPerformed.
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
• Your Source Code window should contain the following lines which is the
actionPerformed method for the Reset button that you need to override:
•Next, we add the codes to implement what we want the Reset Button to do
(replacing the // TODO add your handling code here: line)
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Adding the event handlers
• The action performed by the Reset button is to simply erase all texts in the
textfields. To do this, you will set the texts to all of the four textfields to
empty String.
• Your finished source code should look like this:
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Running the Program
1.
• The final step is to run the program. Right click in the Source Code window
and select Run File.
• Test the Compute button by entering values in the Length & Width textfields
and click the Compute button.
• A sample of the output is as follows:
STEPS FOR ADDING EVENT
HANDLER FOR THE GUI
2. Running the Program
1.
• Test the Reset button by clicking it and all the textfields will be cleared.
• A sample of the output is as follows:
EXERCISE:
• Add another button object to the GUI which is an Exit button
• Add the event handler for the Exit button so that when it is
clicked, the application will close and terminate.
• (you can use the [Link](0) command to terminate a
program)
Exit Button
Textfield
• JTextField nameTF = new JTextField(20);
• Fill data into textfield: [Link](“bla ”);
• Parameter type in textfield must be in String.
• Get data from textfield : [Link]()
• getText() will return in String type.
• Data Conversion:
• String to Integer => [Link](“2”); “2” 2
• String to double => [Link](“2.5”) “2.5” 2.5
• Integer to String => [Link](2) 2 “2”
• double to String => [Link](2.5) 2.5 “2.5”
•
[Link](this,"Please input in numeric value for length and width" );
[Link](); -used to place blinked cursor into length text field
[Link](false); - used to set either the textfileld can be edited (true) or not (false)
Radio Button
isSelected() - used to determine which radio
if ([Link]()) button is selected
status = "married";
if ([Link]())
[Link](); - used to make
status = "bachelor";
radion buttons unselected/ disselected
Combo box
[Link](0); - ask system to
place at the first item at index 0
String course = [Link]([Link]()); // convert Object to String
int sem = [Link]([Link]([Link]()));
String output = "Your selected course is "+course+" and your semester is "+sem;
[Link](output);
getSelectedItem() – used to get the selected item in a combo box