2. Event Handling
▪ Some objects will have events associated with them
▪ These events are triggered when something happens.
▪ Example: JButton objects have a click event, JTextBox
objects have a enter event.
▪ We now have to write code that executes when that
event is triggered – event handling.
▪ Events can be many different things, but we will focus
on action events – clicking on buttons etc.
3. Event Handling
▪ The object creating the event (JButton, JTextBox etc…)
is called the event source.
▪ We need objects to be the event listeners.
Event listeners
Objects that include a method that executes when
there is an event that it is listening for.
Action listeners
Objects that listen for an action event.
4. Event Handling
ActionListener interface
▪ This is an interface (like a class) that we use to create
action listener classes for specific functions.
▪ One of the methods in ActionListener is:
public void actionPerformed(ActionEvent evt)
▪ This is the method that is executed when the
event is triggered.
▪ So when we implement classes from this interface, we
need to implement this method.
5. Event Handling
▪ There is also a new object of a new class:
▪ When there is an event, we can find out details of the
event from ActionEvent object event
▪ In particular, there is a method associated with the
event object called getSource() which returns a pointer
to the object that generated the event i.e. the button or
textbox etc.
public void actionPerformed(ActionEvent event)
7. Event Handling
▪ Where should we put this actionPerformed() method i.e. what
will be our event handler?
▪ There are four ways that we can do this:
1. We can write a separate class that implements this interface
2. We can make our whole frame an implementation of the
interface
3. We can make a class inside of our JFrame class that
implements the interface.
4. We can give the ActionListener class implementation as we are
instantiating the ActionListener object.
8. Event Handling
▪ To show these differences, we will look at the same
simple example:
▪ Given this GUI
▪ When the button is pressed, a message should pop up
and tell the user that they have pressed the button.
9. Event Handling
1. We can write a separate class that implements this interface
and then create an object from this class to handle the event.
▪ Start with a class than inherits from JFrame
10. public class MyGUIDemoV1 extends JFrame {
JButton button1;
public static void main(String[] args) {
//Create an object
MyGUIDemoV1 f = new MyGUIDemoV1("Title goes here");
//Make the object visible
f.setVisible(true);
}
11. MyGUIDemoV1(String title){
//Set up the Frame
setTitle(title);
setSize(500,100);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Get content pane, set LM
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
//Add a button
button1 = new JButton("Button 1");
cp.add(button1);
}
}
12. Event Handling
1. We can write a separate class that implements this interface
and then create an object from this class to handle the event.
▪ Start with a class than inherits from JFrame
▪ Now we need to write a class the implements ActionListener
– Remember: if it implements an interface, it must have the definition for
the method in the interface – in this case actionPerformed()
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed a button!");
}
}
13. Event Handling
1. We can write a separate class that implements this interface
and then create an object from this class to handle the event.
▪ Start with a class than inherits from JFrame
▪ Now we need to write a class the implements ActionListener
▪ Now create an object from this class
ButtonHandler myBH = new ButtonHandler();
▪ Make this object the ActionListener for the button, using the
button’s addActionListener() method.
button1.addActionListener(myBH);
14. Event Handling
2. We can make our whole frame an implementation of the
interface
▪ This means that we need to:
– add “implements ActionListener” to our class
– add the actionPerformed() method to class
▪ Now what do we pass to the button’s addActionListener()
method?
– The object created from the same class is the Action Listener so use this
15. public class MyGUIDemoV2 extends JFrame implements ActionListener {
JButton button1;
public static void main(String[] args) {...}
MyGUIDemoV2(String title){
...
button1.addActionListener(this);
...
}
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed a button!");
}
}
16. Event Handling
3. We can make a class inside of our JFrame class that
implements the interface.
▪ Haven’t done this before but its quite similar to the first option
▪ This allows us to see everything from the rest of our JFrame
class – be careful about the scope of your objects.
▪ This is the concept of Nested Classes.
17. public class MyGUIDemoV3 extends JFrame {
JButton button1;
public static void main(String[] args) {...}
MyGUIDemoV3(String title){
...
ButtonHandler myBH = new ButtonHandler();
button1.addActionListener(myBH);
...
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed a button!");
}
}
}
Now lives inside the MyGUIDemoV3 class
18. Event Handling
▪ We can also have one event listener listening to multiple event
sources
19. public class MyGUIDemoV3 extends JFrame {
JButton button1, button2, button3;
MyGUIDemoV3(String title){
...
ButtonHandler myBH = new ButtonHandler();
button1.addActionListener(myBH);
button2.addActionListener(myBH);
button3.addActionListener(myBH);
...
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed a button!")
}
}
}
20. Event Handling
4. We can give the ActionListener class implementation as we are
instantiating the ActionListener object.
▪ Haven’t done this before…
▪ This is called an Anonymous Inner Class
– Doesn’t have a name
– Only creating a single object from this class.
▪ Particularly helpful when we are working with interfaces – no
need to write a separate class that implements the interface
and then instantiate an object.
21. Event Handling
▪ Before…
interface MyInterface{
void MethodA();
void MethodB();
}
public class MyClass implements MyInterface{
...
public void MethodA() {
System.out.println("Method A implementation.");
}
public void MethodB() {
System.out.println("Method B implementation.");
}
}
22. public class AnonInnerClass{
public static void main(String[] args) {
//Create an object
AnonInnerClass f = new AnonInnerClass();
MyInterface x = new MyInterface() {
public void MethodA() {
System.out.println("Method A implementation.");
}
public void MethodB() {
System.out.println("Method B implementation.");
}
};
x.MethodA();
}
}
No implements anywhere!
23. Event Handling
4. We can give the ActionListener class implementation as we are
instantiating the ActionListener object.
▪ So for our example, we use an Anonymous Inner Class to
define the actionPerformed() method directly – will only apply
to the one component we are passing this object to.
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You pressed a button!");
}
}
);
25. Event Handling
▪ We can also have one event listener listening to multiple event
sources
▪ This isn’t very interesting – lets have different responses for
different events (i.e. different buttons).
▪ We can either…
▪ … use the ActionEvent object to make the actionPerformed()
method behave differently or…
▪ … have different Action Listeners, create objects from each and
then associate each with a different button.
26. Event Handling
Using the ActionEvent object:
▪ The ActionEvent object has a method getSource() which
returns the object that triggered the event.
▪ Can use this to determine what to do
▪ Need to first store this source:
JButton source = event.getSource();
▪ Because the getSource() can return any type of object, we
need to cast it to the type we want:
JButton source = (JButton) event.getSource();
27. Event Handling
Using the ActionEvent object:
▪ Now we can access that objects members…
JOptionPane.showMessageDialog(null, source.getText());
▪ …or even modify the object itself…
source.setText("You clicked me!");
28. Event Handling
Using different Button Handlers:
▪ Have to have different Button Handler classes, then create
different Button Handler objects from each class and add the
corresponding ones to the buttons separately.
ButtonHandlerA myBHA = new ButtonHandlerA();
ButtonHandlerB myBHB = new ButtonHandlerB();
ButtonHandlerC myBHC = new ButtonHandlerC();
button1.addActionListener(myBHA);
button2.addActionListener(myBHB);
button3.addActionListener(myBHC);
29. public class ButtonHandlerA implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed button1!");
}
}
public class ButtonHandlerB implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed button2!");
}
}
public class ButtonHandlerC implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "You pressed button3!");
}
}
31. Event Handling
▪ What if we are dealing with events from different types of
objects?
▪ Modify our GUI to have a JTextField
– If the user clicks the button, the text field should be cleared.
– If the user presses <enter> with the cursor in the text field, the button
text should be what was in the text field.
32. public class MyGUIDemoButtonTF extends JFrame{
JButton button1;
JTextField textField;
public static void main(String[] args) {...}
MyGUIDemoButtonTF(String title){
...
ButtonHandler myBH = new ButtonHandler();
//Add a button
button1 = new JButton("Button 1");
button1.addActionListener(myBH);
...
//Add a JTextField
textField = new JTextField("I am text field!");
textField.addActionListener(myBH);
...
}
33. Event Handling
▪ What if we are dealing with events from different types of
objects?
▪ Different objects will have different attributes and
methods, might require different code.
▪ instanceof operator:
– Returns a bool (true/false)
– True if the left operand is an object of the class (or subclass) of the right
operand
– e.g. JButton button1
– button1 instanceof JButton would be true.
34. public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
JButton source = (JButton) event.getSource();
textField.setText("");
}
else {
JTextField source = (JTextField) event.getSource();
button1.setText(textField.getText());
}
}
}
Is the source of the
event a button?
36. GUI components
Checkbox
▪ JCheckBox – from the javax.swing package
▪ Constructor: String is the text next to the check box
▪ Very common to group check boxes in arrays
▪ Can trigger an ActionEvent as well as an ItemEvent
String[] checkBoxText = {“Option 1", “Option 2", “Option 3"};
JCheckBox[] checkBox = new JCheckBox[checkBoxText.length];
for (int i = 0; i < checkBox.length;i++)
checkBox[i] = new JCheckBox(checkBoxText[i]);
37. Event Handling
▪ This has an ItemListener (like an ActionListener)
▪ There is an ItemEvent (like an ActionEvent) associated with it.
▪ The ItemEvent object has a getStateChange() method which
takes values either ItemEvent.SELECTED or ItemEvent.DESELECTED
▪ In practice, ItemListener can be a bit tricky, particularly when
using JOptionPane methods
▪ Can use ActionListener instead.
38. Event Handling
Example
▪ Make a GUI where the user can select
all the sport they like.
▪ After every tick or untick, a text area
should make a note of the change.
▪ When they click OK, the text area
should show all the options that have
been checked.
39. Event Handling
▪ We are going to make our frame the Event Listener
public class MyCheckBoxesGUI extends JFrame implements
ActionListener, ItemListener
▪ Set up check boxes – it is common to put them in an array
JCheckBox[] checkBox;
▪ Create an array with the labels for the check boxes:
String[] checkBoxText = {"Soccer", "Cricket", "Rugby",
"Swimming", "Formula 1"};
40. Event Handling
▪ Create the check box array:
checkBox = new JCheckBox[checkBoxText.length];
▪ Create each check box, add ItemListener, add checkbox to panel
for (int i = 0; i < checkBox.length;i++) {
checkBox[i] = new JCheckBox(checkBoxText[i]);
checkBox[i].addItemListener(this);
checkPanel.add(checkBox[i]);
}
41. Event Handling
▪ Define the itemStateChanged() method:
public void itemStateChanged(ItemEvent event) {
JCheckBox source = (JCheckBox) event.getSource();
displayTextArea.setText(source.getText() + " is "+
((event.getStateChange() == ItemEvent.SELECTED) ?
"selected.":"deselected."));
}
42. Event Handling
▪ Define the actionPerformed() method:
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
String s = "These are your favourite sports: n";
for (int i = 0; i < checkBox.length;i++)
if (checkBox[i].isSelected())
s = s + checkBox[i].getText() + "n";
displayTextArea.setText(s);
}
}