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.

Slides:



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

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
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.
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 19 Graphics User Interfaces (GUIs)
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
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.
Io package as Java’s basic I/O system continue’d.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
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.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
GUI programming Graphical user interface-based programming.
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,
1.00 Lecture 16 The Swing Event Model 1. 2 GUI Event Model Operating system (Windows, JVM) runs the show: – Monitors keystroke, mouse, other I/O events.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS Lecture 01 Frames and Components and events Lynda Thomas
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/15) MVC and Swing Joel Adams and Jeremy Frens Calvin College.
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.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
CompSci Event Handling. CompSci Event Handling The Plan  Sequential (Single Thread) Model  Event Model  Making the GUI interactive  Examples.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Creating a GUI Class An example of class design using inheritance and interfaces.
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.
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.
Event Handling CS 21a: Introduction to Computing I First Semester,
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
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.
GUI Programming using Java - Event Handling
Lecture 15 Basic GUI programming
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CSC 205 Programming II Lecture 5 AWT - I.
Observer Pattern Context:
Web Design & Development Lecture 11
A First Look at GUI Applications
Processing Timer Events
Ellen Walker Hiram College
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
GUI Programming III: Events
Event-driven programming for GUI
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Introduction to Event Handling
CiS 260: App Dev I Chapter 6: GUI and OOD.
Presentation transcript:

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 user. But how do GUIs interact with users? How do applications recognize when the user has done something?

package swinglab; import java.awt.*; import javax.swing.*; public class ClickReporter extends JFrame { public ClickReporter() { JButton myButton = new JButton("Click here"); Container cp = getContentPane(); cp.add(myButton); setTitle("Click Printer"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); show(); } public static void main(String[] args) { ClickReporter cr = new ClickReporter(); } ClickReporter

ClickPrinter Listener package swinglab; import java.awt.event.*; class ClickPrinter implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button was pressed"); }

Adding a Listener public ClickReporter() { JButton myButton = new JButton("Click here"); ClickPrinter printer = new ClickPrinter(); click.addActionListener(printer); Container cp = getContentPane(); cp.add(myButton); setTitle("Click Printer"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); show(); }

ClickReporter Each time you click the button a message is displayed in a console window. Button was pressed Click here

Event Handling Diagram e.g. button, menu, text fields

Event Handling To be able to handle events in Java we need 3 things: –event sources –event objects –event listeners

Event Sources Event sources are components that can recognize user action: menus, buttons, text fields etc. Event sources have methods to add event listeners to them like addActionListener Event source reports on events and notifies all its listeners

Event Source In our ClickReporter class we create an event source, a JButton called myButton: JButton myButton = new JButton("Click here"); Click here

Event Objects Objects that represent a user action (e.g. mouse click) – contain detailed information about the event. When an event happens an event source sends an event object to its event listeners EventObject is the superclass –ActionEvent, MouseEvent, etc. are the subclasses that we use

Event Objects In our example, the event source – JButton myButton generates an event object representing a mouse click. We are not going into details of EventObjects – we will need them only as arguments to the method actionPerformed in event listeners.

Event Listeners Event listeners are objects that respond when an event occurs Any object, whose class implements the ActionListener interface, can be an event listener. If the event listener has been added to an event source, the listener will be called when an event occurs on that source.

ActionListener interface Look it up at the API in the package java.awt.event : public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Event Listener In ClickReporter class we have an event listener – ClickPrinter object called printer : ClickPrinter printer = new ClickPrinter(); and add this listener to our JButton click : click.addActionListener(printer);

create an event source: JButton myButton = new JButton("Click here"); create an event listener: ClickPrinter printer = new ClickPrinter(); add listener to the source: click.addActionListener(printer);

Add the following data fields to your ClickReporter class: private JLabel counterLabel; private int counter = 0; Add the following three lines to the ClickReporter constructor: cp.setLayout(new FlowLayout()); ClickCounter cc = new ClickCounter(this); click.addActionListener(cc);

Add these lines to your constructor: counterLabel = new JLabel( "The number of clicks is 0"); cp.add(counterLabel); Add this method to ClickReporter : void incrementCounter(){ counterLabel.setText( "The number of clicks is " + (++counter)); pack(); }

In your swinglab package create ClickCounter: package swinglab; import java.awt.event.*; class ClickCounter implements ActionListener { private ClickReporter clickReporter; ClickCounter(ClickReporter c) { clickReporter = c; } public void actionPerformed(ActionEvent e){ clickReporter.incrementCounter(); }

ClickCounter Diagram JButton ClickCounter ClickReporter actionPerformed incrementCounter Button is pressed and notifies ClickCounter ClickCounter tells ClickReporter to increment its counter

A Calculator Listener package swinglab; import java.awt.event.*; class CalcListener implements ActionListener { private Calc calculator; CalcListener(Calc c) { calculator = c; } public void actionPerformed(ActionEvent e) { calculator.calculatePressed(); }

void calculatePressed() { double n1 = Double.parseDouble(num1.getText()); double n2 = Double.parseDouble(num2.getText()); String op = (String)operation.getSelectedItem(); double ans; if (op.equals(Calc.ADD_OP)) ans = n1 + n2; else if (op.equals(Calc.SUB_OP)) ans = n1 - n2; else if (op.equals(Calc.MUL_OP)) ans = n1 * n2; else ans = n1 / n2; answerLabel.setText("Answer: " + ans); pack(); } Add this method to Calc class:

Add the Calc Listener In the Calc constructor, add an instance of CalcListener as a listener to the calculate button CalcListener cl = new CalcListener(this); calculate.addActionListener(cl);

Quiz Question 1 Q: It's annoying to make a separate class for each listener. If any class can implement an interface, can't Calc implement ActionListener and listen for the events itself? A: Yes

Quiz Question 2 Q: Is it a good idea to have Calc be a listener for itself? A: No. Calc is public, and if Calc implements ActionListener, then any outside class can use Calc to listen for unrelated events. Calc is only designed to handle Calc 's own events.

Uh oh... What happens when you type letters into the textfields and click the calculate button? Exceptions are thrown!

Exception Handling Catch those exceptions and display an error message window describing the error to the user. To show the error message window use the method JOptionPane.showMessageDialog Hint: the parentComponent should be the Calc object itself

Solution void calculatePressed() { double n1 = 0, n2 = 0; try { n1 = Double.parseDouble(num1.getText()); n2 = Double.parseDouble(num2.getText()); } catch(NumberFormatException e) { JOptionPane.showMessageDialog(this, "Must type two numbers, dummy!", "Not Numbers!", JOptionPane.ERROR_MESSAGE); } String op = (String)operation.getSelectedItem(); double ans; if (op.equals(Calc.ADD_OP)) ans = n1 + n2; else if (op.equals(Calc.SUB_OP)) ans = n1 - n2; else if (op.equals(Calc.MUL_OP)) ans = n1 * n2; else ans = n1 / n2; answerLabel.setText("Answer: " + ans); }