Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.

Slides:



Advertisements
Similar presentations
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Advertisements

Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Event Handling Events and Listeners Timers and Animation.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Simple user interfaces Liang, Chapter 10 (some parts) Liang Chapter 11 (some parts)
Event-Driven Programming
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CS Lecture 01 Frames and Components and events Lynda Thomas
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Event Driven Programming. Event-driven Programming In the early days of computing communication with the outside world was accomplished using a technique.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 Event-Driven Programming.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
For (int i = 1; i
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
Events and Event Handling
Graphical User Interfaces
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Chapter 12 Event-Driven Programming
Web Design & Development Lecture 11
Ellen Walker Hiram College
GUI Programming III: Events
Event-driven programming for GUI
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate what happens and when Sample event: a button click...or mouse movement (see Horstmann, ch 12: Event handling)

Events An Event is caused by a user’s action (e.g. clicking) The source of the event is the component generating the event (e.g. a JButton ) The Event Type depends on the nature of the event and of the component: –A JButton produces an ActionEvent when clicked –A JTextArea produces an ActionEvent when return is typed –A Window (e.g. a Jframe ) produces a WindowEvent when opened or closed,etc. All events are subclasses of the EventObject class: import java.awt.event.*; // to get EventObject How do we write code to respond to an event? We use code that “listens” for an event to happen.

Noticing events: A Button Click A JFrame contains a JButton To respond when the JButton is clicked, we create an actionListener object to listen for the action of that JButton being clicked. That actionListener object must contain a method called public void ActionPerformed(ActionEvent e) The actionListener object registers with the Jbutton. Thereafter, whenever the JButton is clicked, it calls the actionPerformed(ActionEvent e) method in the listener. The actionPerformed (ActionEvent e) method does whatever we want to happen when the button is clicked. count myActionListener { actionPerformed(ActionEvent e){ JOptionPane.showMessageDialog(“Button click!”); } event e: Click Listener registers with JButton JOptionPane Button Clicked!

ActionEvent and ActionListener A button click is an ActionEvent Therefore anything that listens for a button click must be an ActionListener Any object that is an ActionListener must have a method like this: –void actionPerformed(ActionEvent e) This method contains code which will be executed when the listener receives notice of an event ActionListener is an interface. Any object that is going to listen for actions must implement the ActionListener interface. Implementing the ActionListener interface is simply a promise to have a method: void ActionPerformed(ActionEvent e)

Defining an actionListener class class myCountListener implements ActionListener{ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,”Count button clicked!"); } This class defines a set of objects that implement ActionListener and provide the actionPerformed method. We’ll use an object from this class to listen for clicks to the “count” button in a JFrame. Anything can implement the ActionListener interface, as long as it provides the public void actionPerformed(ActionEvent e) Method. Later we’ll see a more complicated class that implements this interface.

Registering a listener object with a source (a Jbutton) JButton myCountButton = new JButton(“count"); myCountListener listener = new myCountListener(); myCountButton.addActionListener(listener); This snippet of code creates a JButton object, then creates a myCountListener object, the registers that listener with that button (adds the listener object as a listener to the button). This registration step creates the link between the button and the listener: after this step, when the button is clicked, the actionPerformed() method in the listener object will be executed. Next: putting it all together.

Making the JFrame class implement ActionListener Any class at all can implement ActionListener, if it provides the actionPerformed() method. Its most useful to make the class that draws our windows (our JFrames ) also implement ActionListener, so that objects from that clss not only draw buttons but can respond to events on those buttons. To do this we change our myButtonJFrame class so that it proves an actionPerformed() method as well as constructing the JFrame object. I’ll call this new class EventButtonJFrame

import javax.swing.*; import java.awt.*; import java.awt.event.*; // we need event classes class EventButtonJFrame extends Jframe implements ActionListener{ JTextArea myTextArea = new JTextArea(6,30), JButton myCountButton = new JButton("Count"); // make button JPanel buttonPanel = new JPanel(); EventButtonJFrame (){ // constructor super(“myButtonJFrame"); myCountButton.addActionListener(this); // register this class as the listener // for myCountButton buttonPanel.setLayout(new GridLayout(4,0)); buttonPanel.add(myCountButton); // add button to panel Container content = this.getContentPane(); content.setLayout(new BorderLayout()); content.add(myTextArea,BorderLayout.CENTER); content.add(buttonPanel, BorderLayout.EAST); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,”Count button clicked!"); } This class draws our button frame, but also implements ActionListener and provides the actionPerformed() method

Doing something useful! The actionPerformed method in the previous programs doesn’t really do anything useful. To get that method to do something useful, we could, for example, give it access to the JTextArea object created in our JFrame window. To do this, we will 1) Make the JTextArea object a generally accessible variable in the Jframe object. To do this, we put JTextArea myTextArea = new JTextArea("this is a text area",6,30); at the top of the EventButtonJFrame class definition. 2) Refer to the text in that JtextArea object in the actionPerformed method, so that when our count button is clicked, we can return some useful information. We can get the text inside the JTextArea object by saying myTextArea.getText(); (we can change that text by saying something like: myTextArea.setText(“this is the new text”);

import javax.swing.*; import java.awt.*; import java.awt.event.*; // we need event classes class EventButtonJFrame extends JFrame implements ActionListener{ JTextArea myTextArea = new JTextArea("this is a text area",6,30); JButton myCountButton = new JButton("count"); // create button JPanel buttonPanel = new JPanel(); EventButtonJFrame (){ super("myButtonJFrame"); myCountButton.addActionListener(this); // add listener buttonPanel.setLayout(new GridLayout(4,0)); buttonPanel.add(myCountButton); // add button Container content = this.getContentPane(); content.setLayout(new BorderLayout()); content.add(myTextArea,BorderLayout.CENTER); // add text area content.add(buttonPanel, BorderLayout.EAST); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, “The number of characters in JTextArea is "+myTextArea.getText().length() ); } Whenever the count button is clicked, we get a message telling us how many characters are currently in myTextArea. Download from herehere

class testEventButtonJFrame { public static void main(String[] args) { EventButtonJFrame frame = new EventButtonJFrame(); frame.setSize(300,200); frame.setLocation(300,330); frame.setVisible(true); } This program will respond to a click on the count button by popping up a text message telling the user how many characters are currently entered in the JTextArea of the EventButtonJFrame object. Note that for this program to compile and run properly, it must be in a file called testEventButtonJFrame.java. This is because the class with the main method (the one that will actually run) is the testEventButtonJFrame class. // continued…

A listener with two buttons (download here)here If we want our actionListener to respond to more than 1 button, we have to change the actionPerformed method so that it checks which button was source of the current event. We do this as follows: Declare the two buttons as class-level variables; at top of the class, put: JButton myCountButton = new JButton("count"); JButton myClearButton = new JButton("clear"); In the constructor for the class, register both buttons with the listener (and add each button to the JPanel as required): myCountButton.addActionListener(this); myClearButton.addActionListener(this); In the actionPerformed method, check which button was the source of the current ActionEvent e, and respond accordingly: if (e.getSource().equals(myCountButton)) {… do whatever } if (e.getSource().equals(myClearButton)) {… do whatever }

Listening for MouseEvents Action events are clicks on a button on the screen. We can also listen for “mouse events”: movements of the mouse, clicking on the mouse, etc. The listener interface we use is different: –MouseListener Rather than ActionListener (used earlier). Rather than registering this object as an ActionListener, we register it as a mouseListener ( addMouseListener ). We also make sure the object implements the methods required to be a MouseListener (for ActionListener, only one method, actionPerformed(ActionEvent e) was needed. MouseListener requires more methods)

What methods must an object have to implement MouseListener? Check the definition for MouseListener in the API: We must implement all these to implement the interface Method Summary void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed andmouseClickedMouseEvent released) on a component. void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. mouseEnteredMouseEvent void mouseExited(MouseEvent e) Invoked when the mouse exits a component. mouseExitedMouseEvent void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. mousePressedMouseEvent void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. mouseReleasedMouseEvent (download here)here

Conclusion GUI construction and control is not complicated, but there are loads of details involved. You don’t need to know all these details: my aim has been to give a general idea of what goes on in GUI construction and in event-driven programming. If you’re interested, you can look up the various classes discussed here in the Java API: (click on ‘API specifications’ under ‘reference’, and then pick the edition of J2SE you are using: currently probably ). There are very useful tutorials on JFrame use, event-driven programming and other aspects of Java programming in the API.