SlideShare a Scribd company logo
1 of 42
Download to read offline
Lecture 8
GUIs and Event Driven Programming
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.
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.
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.
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)
Event Handling
Four ways
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.
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.
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
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);
}
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);
}
}
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!");
}
}
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);
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
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!");
}
}
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.
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
Event Handling
▪ We can also have one event listener listening to multiple event
sources
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!")
}
}
}
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.
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.");
}
}
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!
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!");
}
}
);
One listener, multiple sources
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.
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();
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!");
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);
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!");
}
}
Multiple listener,
multiple sources
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.
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);
...
}
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.
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?
Checkboxes and ItemListeners
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]);
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.
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.
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"};
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]);
}
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."));
}
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);
}
}

More Related Content

Similar to Lecture 8.pdf

Similar to Lecture 8.pdf (20)

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
09events
09events09events
09events
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Event handling
Event handlingEvent handling
Event handling
 
ACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptxACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptx
 
Swing_Introduction.ppt
Swing_Introduction.pptSwing_Introduction.ppt
Swing_Introduction.ppt
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
Gui builder
Gui builderGui builder
Gui builder
 
10 awt event model
10 awt event model10 awt event model
10 awt event model
 
A Simple Java GUI Application.pptx
A Simple Java GUI Application.pptxA Simple Java GUI Application.pptx
A Simple Java GUI Application.pptx
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
 
Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3
 
Introj Query Pt2
Introj Query Pt2Introj Query Pt2
Introj Query Pt2
 
Jp notes
Jp notesJp notes
Jp notes
 

More from SakhilejasonMsibi (11)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 4 part 2.pdf
Lecture 4 part 2.pdfLecture 4 part 2.pdf
Lecture 4 part 2.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture2.pdf
Lecture2.pdfLecture2.pdf
Lecture2.pdf
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...Amil baba
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Toolssoginsider
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Studentskannan348865
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxMustafa Ahmed
 
Insurance management system project report.pdf
Insurance management system project report.pdfInsurance management system project report.pdf
Insurance management system project report.pdfKamal Acharya
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdfAlexander Litvinenko
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxCHAIRMAN M
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptjigup7320
 
Artificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfArtificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfKira Dess
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxMANASINANDKISHORDEOR
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Studentskannan348865
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...IJECEIAES
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfragupathi90
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...archanaece3
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...IJECEIAES
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxKarpagam Institute of Teechnology
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationEmaan Sharma
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1T.D. Shashikala
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniR. Sosa
 

Recently uploaded (20)

NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 
Insurance management system project report.pdf
Insurance management system project report.pdfInsurance management system project report.pdf
Insurance management system project report.pdf
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
Artificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfArtificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdf
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Students
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & Modernization
 
Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1Research Methodolgy & Intellectual Property Rights Series 1
Research Methodolgy & Intellectual Property Rights Series 1
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney Uni
 

Lecture 8.pdf

  • 1. Lecture 8 GUIs and Event Driven Programming
  • 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); } }