Graphical User Interface (GUI) IIGraphical User
Interface (GUI) II
Objectives
Differentiate the use of event handling for each component.
Apply appropriate event handling based on given problem.
Transform program from java application to java applet and vice versa.
Event-Driven Programming
In event-driven programming, code is executed upon activation of events.
Ex: a button click, or mouse movement
3
Events and Event Source An event can be defined as a type of signal to the
program that something has happened.
The event 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
7
Source Event TypeUser 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
In detail, refer to Table 16.1 pg 559
Listeners, Registartions, and Handling Events
Java uses a delegation-based model for event handling
An external user action on a source object triggers an event An object interested in the event receives the event The latter object is called a listener
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. 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
9
Selected Event Handlers
10
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)
In detail, refer to Table 16.2 pg 561
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
13
source: JButton
+addActionListener(ActionListener listener)
listener: ListenerClass
ActionListener
+actionPerformed(ActionEvent event)
Register by invoking source.addActionListener(listener);
ListenerClass listener = new ListenerClass();
JButton jbt = new JButton("OK");
jbt.addActionListener(listener);
class ListenerClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
S.o.p (“Button “+ e.getActionCommand()+ “ is clicked.”);}
Example:
Class must implement the listener interface (ex: ActionListener). and method to handle the event (ex: actionPerformed())
The listener object must register with source object (ex: button) Done by invoking the addActionListener in the button object
Ex::
public class TestActionButton extends JFrame implements ActionListener{
JButton btn = new JButton(“Click Here"); btn.addActionListener(this); public void actionPerformed(ActionEvent e) { }}
Registration method (XEvent addXListener)
ActionEvent
The components that involved with this event are: JButton – clicka a button JMenuItem – select a menu item JTextField – press return on a text field
Event listener interface – ActionListener
Event handler method
public void actionPerformed(ActionEvent e)
java.awt.event.ActionEvent
16
java.awt.event.ActionEvent
+getActionCommand(): String
+getModifier(): int
+getWhen(): long
Returns the command string associated with this action. For a button, its text is the command string.
Returns the modifier keys held down during this action event.
Returns the timestamp when this event occurred. The time is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
java.util.EventObject
+getSource(): Object
Returns the object on which the event initially occurred.
java.awt.event.AWTEvent
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class UjiActionButang extends JFrame implements ActionListener{ JButton btg = new JButton("Sila Klik"); JTextField txtField = new JTextField(10); JLabel lbl = new JLabel(" ");
public UjiActionButang() { super("Melaksanakan ActionEvent"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); bekas.add(btg); btg.addActionListener(this); bekas.add(txtField); bekas.add(lbl); setSize(300,200); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) { lbl.setText("Terima Kasih"); txtField.setText("Sama-sama"); } } public static void main(String[] arg) { UjiActionButang teks = new UjiActionButang(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
To display label, and text on text field when button is clicked
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class ActionTextField extends JFrame implements ActionListener{ JLabel lbl = new JLabel("Nama "); JTextField txtField = new JTextField(10); public ActionTextField() { super("Melaksanakan ActionEvent- TextField"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); bekas.add(lbl); bekas.add(txtField); txtField.addActionListener(this); setSize(300,200); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()== txtField) { JOptionPane.showMessageDialog(this,"Nama anda = "+ txtField.getText(),"Pemberitahuan", JOptionPane.INFORMATION_MESSAGE); } } public static void main(String[] arg) { ActionTextField teks = new ActionTextField(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
To display name from text field on dialog box
when pressing <enter> on text field
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class ActionButton extends JFrame implements ActionListener{ JLabel lbl = new JLabel("Nama "); JTextField txtField = new JTextField(10); JButton btg = new JButton("Klik"); JTextArea txtArea = new JTextArea("Ali",10,6); public ActionButton() { super("Melaksanakan ActionEvent- Butang"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); bekas.add(lbl); bekas.add(txtField); bekas.add(btg); bekas.add(txtArea); btg.addActionListener(this); setSize(300,200); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) { txtArea.append("\n"+txtField.getText()); } } public static void main(String[] arg) { ActionButton teks = new ActionButton(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
To append text on text area when button is clicked
import java.awt.*;import javax.swing.*;import java.awt.event.*;public class UjiActionMenu extends JFrame implements ActionListener{ JFrame frame = new JFrame(); JMenuBar jmb = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem baru= new JMenuItem("New"); JMenuItem buka= new JMenuItem("Open");
public UjiActionMenu() { frame.setTitle("membuat menu"); baru.addActionListener(this); fileMenu.add(baru); fileMenu.add(buka); jmb.add(fileMenu); frame.setJMenuBar(jmb); frame.setSize(400,200); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == baru) JOptionPane.showMessageDialog(this,"Anda telah memilih menu New", "Pemberitahuan",JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] arg) { UjiActionMenu teks = new UjiActionMenu(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }} Display dialog box when menu item is clicked
comboBox
Generate two types of event ActionEvent ItemEvent
For the case of ItemEvent: Event listener Interface : ItemListener Event handler method public void ItemStateChanged(ItemEvent e)
○ When select an item in the combo box
Index for the first item in the combo box will be started by 0..n-1.
comboBox
javax.swing.JComboBox
+JComboBox()
+JComboBox(items: Object[])
+addItem(item: Object): void
+getItemAt(index: int): Object
+getItemCount(): int
+getSelectedIndex(): int
+setSelectedIndex(index: int): void
+getSelectedItem(): Object
+setSelectedItem(item: Object): void
+removeItem(anObject: Object): void
+removeItemAt(anIndex: int): void
+removeAllItems(): void
Creates a default empty combo box.
Creates a combo box that contains the elements in the specified array.
Adds an item to the combo box.
Returns the item at the specified index.
Returns the number of items in the combo box.
Returns the index of the selected item.
Sets the selected index in the combo box.
Returns the selected item.
Sets the selected item in the combo box.
Removes an item from the item list.
Removes the item at the specified index in the combo box.
Removes all items in the combo box.
javax.swing.JComponent
22
Using theitemStateChanged Handler
public void itemStateChanged(ItemEvent e)
{ // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem();}
23
When a new item is selected, itemStateChanged() for ItemEvent is invoked .
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class UjiItemEventComboBox extends JFrame implements ItemListener{ JComboBox jcb = new JComboBox(); public UjiItemEventComboBox() { super("Membuat combobox"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); jcb.addItem("wira"); jcb.addItem("waja"); jcb.addItemListener(this); bekas.add(jcb); setSize(400,200); setVisible(true); } public void itemStateChanged(ItemEvent e) { if (e.getSource()== jcb) { if (e.getStateChange() == ItemEvent.SELECTED) {
String s1 = (String) jcb.getSelectedItem(); JOptionPane.showMessageDialog(this,"Anda telah memilih "+s1,"Maklumat", JOptionPane.INFORMATION_MESSAGE);
} } }
ItemEvent: Display item on dialog box when item in Combo Box is selected
public static void main(String[] arg) { UjiItemEventComboBox teks = new UjiItemEventComboBox(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class UjiActionEventComboBox extends JFrame implements ActionListener{ JComboBox jcb = new JComboBox(); JButton btg = new JButton("Klik");
public UjiActionEventComboBox() { super("Membuat combobox"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); jcb.addItem("wira"); jcb.addItem("waja"); btg.addActionListener(this); bekas.add(jcb); bekas.add(btg); setSize(400,200); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) { String s1 = (String)jcb.getSelectedItem(); JOptionPane.showMessageDialog(this,"Anda telah memilih "+s1,“ Maklumat",JOptionPane.INFORMATION_MESSAGE); } } public static void main(String[] arg) { UjiActionEventComboBox teks = new UjiActionEventComboBox(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
ActionEvent: Display selected item on dialog box when a button is clicked
ListSelectionEvent - JList
Generates javax.swing.event.ListSelectionEvent to notify the listeners of the slections
Event listener interface : ListSelectionListener Event handler interface:
public void valueChanged(ListSelectionEvent e)○ When select item(s) in JList
Index for the first item in the JList will be started by 0..n-1.
ListSelectionEvent - JList
javax.swing.JList
+JList()
+JList(items: Object[])
+getSelectedIndex(): int
+setSelectedIndex(index: int): void
+getSelectedIndices(): int[]
+setSelectedIndices(indices: int[]): void
+getSelectedValue(): Object
+getSelectedValues(): Object[]
+getVisibleRowCount(): int
+setVisibleRowCount(count: int): void
+getSelectionBackground(): Color
+setSelectionBackground(c: Color): void
+getSelectionForeground(): Color
+setSelectionForeground(c: Color): void
+getSelectionMode(): int
+setSelectionMode(selectionMode: int):
Creates a default empty list.
Creates a list that contains the elements in the specified array.
Returns the index of the first selected item.
Selects the cell at the specified index.
Returns an array of all of the selected indices in increasing order.
Selects the cells at the specified indices.
Returns the first selected item in the list.
Returns an array of the values for the selected cells in increasing index order.
Returns the number of visible rows displayed without a scrollbar. (default: 8)
Sets the preferred number of visible rows displayed without a scrollbar.
Returns the background color of the selected cells.
Sets the background color of the selected cells.
Returns the foreground color of the selected cells.
Sets the foreground color of the selected cells.
Returns the selection mode for the list.
Sets the selection mode for the list.
javax.swing.JComponent
28
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;
class UjiSelectionEventList extends JFrame implements ListSelectionListener{ String[] jenisWarna= {"merah","hijau","kuning","jingga","biru"}; JList senaraiWarna; public UjiSelectionEventList() { super("Membuat JList"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); senaraiWarna = new JList(jenisWarna); senaraiWarna.addListSelectionListener(this); senaraiWarna.setVisibleRowCount(3); senaraiWarna.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); bekas.add(new JScrollPane(senaraiWarna)); setSize(300,200); setVisible(true); }
public void valueChanged(ListSelectionEvent e) { if (e.getSource()== senaraiWarna) {
String s1 = (String)senaraiWarna.getSelectedValue(); JOptionPane.showMessageDialog(this,s1,"maklumat", JOptionPane.INFORMATION_MESSAGE);
} }
SelectionEvent: Display selected item when item in JList is clicked
public static void main(String[] arg) { UjiSelectionEventList list = new UjiSelectionEventList(); list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;
class DataListEventt extends JFrame implements ActionListener{ String[] jenisWarna= {"merah","hijau","kuning","jingga","biru"}; JList senaraiWarna; JButton btg = new JButton("Klik"); public DataListEventt() { super("Membuat JList"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout()); senaraiWarna = new JList(jenisWarna); senaraiWarna.setVisibleRowCount(3); senaraiWarna.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); bekas.add(new JScrollPane(senaraiWarna)); bekas.add(btg); btg.addActionListener(this); setSize(300,200); setVisible(true); }
public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) {
String s1 = (String)senaraiWarna.getSelectedValue(); JOptionPane.showMessageDialog(this,s1,"maklumat", JOptionPane.INFORMATION_MESSAGE);
} }
ActionEvent: Display selected item in JList when a button is clicked
public static void main(String[] arg) { DataListEventt list = new DataListEventt(); list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
ItemEvent - RadioButton
Event Listener Interface : ItemListener Event handler method :
public void ItemStateChanged(ItemEvent e)○ Click a radio button
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class UjiItemListenerRadioButton extends JFrame implements ItemListener { JRadioButton rdButton1,rdButton2; public UjiItemListenerRadioButton() { super("Membuat RadioButton"); Container bekas = getContentPane();
bekas.setLayout(new FlowLayout());
rdButton1 = new JRadioButton("wira"); rdButton2 = new JRadioButton("Waja",true);
rdButton1.addItemListener(this); rdButton2.addItemListener(this); bekas.add(rdButton1); bekas.add(rdButton2);
ButtonGroup butang = new ButtonGroup(); butang.add(rdButton1); butang.add(rdButton2); setSize(400,200); setVisible(true); }
ItemEvent: Display item on dialog box when a radio button is clicked
public void itemStateChanged(ItemEvent e) { if (e.getSource()== rdButton1) { if (e.getStateChange() == ItemEvent.SELECTED)
JOptionPane.showMessageDialog(this,"kereta wira","Maklumat", JOptionPane.INFORMATION_MESSAGE);
} if (e.getSource()== rdButton2) { if (e.getStateChange() == ItemEvent.SELECTED)
JOptionPane.showMessageDialog(this,"kereta waja","Maklumat", JOptionPane.INFORMATION_MESSAGE);
} }
public static void main(String[] arg) { UjiItemListenerRadioButton teks = new UjiItemListenerRadioButton(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class DataRadioButton extends JFrame implements ActionListener { JRadioButton rdButton1,rdButton2; JButton btg = new JButton("Klik"); String kereta;
public DataRadioButton() { super("Membuat RadioButton"); Container bekas = getContentPane();
bekas.setLayout(new FlowLayout());
rdButton1 = new JRadioButton("wira"); rdButton2 = new JRadioButton("Waja",true); bekas.add(rdButton1); bekas.add(rdButton2); bekas.add(btg); btg.addActionListener(this); ButtonGroup butang = new ButtonGroup(); butang.add(rdButton1); butang.add(rdButton2); setSize(400,200); setVisible(true); }
ActionEvent: Display selected item from radio button when a button is clicked
public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) { if (rdButton1.isSelected()) kereta = "Wira"; if (rdButton2.isSelected()) kereta = "Waja"; JOptionPane.showMessageDialog(this,kereta,"maklumat", JOptionPane.INFORMATION_MESSAGE); } }
public static void main(String[] arg) { DataRadioButton teks = new DataRadioButton(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
ItemEvent - CheckBox
Event Listener Interface : ItemListener Event handler metod :
public void ItemStateChanged(ItemEvent e)○ Click a check box
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class UjiItemEventCheckBox extends JFrame implements ItemListener{ JCheckBox chkBox1,chkBox2; public UjiItemEventCheckBox() { super("Membuat CheckBox"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout());
chkBox1 = new JCheckBox("Wira"); chkBox1.addItemListener(this); chkBox2 = new JCheckBox("Waja"); bekas.add(chkBox1); bekas.add(chkBox2); setSize(400,200); setVisible(true); } public void itemStateChanged(ItemEvent e) { if (e.getSource()== chkBox1) { if (e.getStateChange() == ItemEvent.SELECTED)
JOptionPane.showMessageDialog(this,"Di tanda","Maklumat", JOptionPane.INFORMATION_MESSAGE);
} } public static void main(String[] arg) { UjiItemEventCheckBox teks = new UjiItemEventCheckBox(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
ItemEvent: Display a message when clicking a check box
import java.awt.*;import javax.swing.*;import java.awt.event.*;
public class DataCheckBox extends JFrame implements ActionListener{ JCheckBox chkBox1,chkBox2; JButton btg = new JButton("Klik"); String kereta;
public DataCheckBox() { super("Membuat CheckBox"); Container bekas = getContentPane(); bekas.setLayout(new FlowLayout());
chkBox1 = new JCheckBox("Wira"); chkBox2 = new JCheckBox("Waja"); bekas.add(chkBox1); bekas.add(chkBox2); bekas.add(btg); btg.addActionListener(this); setSize(400,200); setVisible(true); }
ActionEvent: Display selected item from check box when button is clicked
public void actionPerformed(ActionEvent e) { if (e.getSource()== btg) { if (chkBox1.isSelected()) kereta = "Wira"; if (chkBox2.isSelected()) kereta = "Waja"; JOptionPane.showMessageDialog(this,kereta,"maklumat",
JOptionPane.INFORMATION_MESSAGE); } }
public static void main(String[] arg) { DataCheckBox teks = new DataCheckBox(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}