Chapter 8 Event Handling.

Slides:



Advertisements
Similar presentations
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Advertisements

Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 : Event-Driven Programming and GUI Objects.
Chapter 7 Event-Driven Programming and Basic GUI Objects.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 14 GUI and Event-Driven Programming.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
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.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
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.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
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,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Graphical User Interface in Java
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.
Even-Driven Programming and basic Graphical User Interface.
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.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
1 Class 6. 2 Objectives Objectives Enable your applications to perform actions in response to JButton clicks Get the text the user enters in a textfield.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
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.
DCS2133 Object Oriented Programming Graphical User Interface & Event-Driven Programming.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-2 ( Book Chapter 14) GUI and Event-Driven Programming.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
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.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Multiple buttons and action calls
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.
CompSci 230 S Programming Techniques
Web Design & Development Lecture 11
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
CSE 114 – Computer Science I Event Programming
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 -->
Event-driven programming for GUI
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Introduction to Event Handling
Chapter 7-2 (Book Chapter 14)
Chapter 7 (Book Chapter 14)
Constructors, GUI’s(Using Swing) and ActionListner
Chapter 7-2 (Book Chapter 14)
Chapter 5 Processing Input with Applets
GUI and Event-Driven Programming
Graphical User Interface
Presentation transcript:

Chapter 8 Event Handling

Event Handling event source objects event listener objects An action involving a GUI object, such as clicking a button, is called an event. The mechanism to process events is called event handling. Event handling is implemented by two types of objects: event source objects event listener objects JButton and other GUI objects are event source objects. Any object can be designated as event listener objects.

Event Source and Event Listeners Objects An event source is a GUI object where an event occurs. We say an event source generates events. Buttons, text boxes, list boxes, and menus are common event sources in GUI-based applications. An event listener object is an object that includes a method that gets executed in response to the generated events. A listener must be associated, or registered, to a source, so it can be notified when the source generates events. A single event source can generate more than one type of events. When an event is generated, a corresponding event listener is notified. Whether there is a designated listener or not, event sources generates events. If there's a no matching listeners, generated events are simply ignored.

Connecting Source and Listener event source event listener notify JButton Handler register This diagram shows the relationship between the event source and listener. First we register a listener to an event source. Once registered, whenever an event is generated, the event source will notify the listener. A listener must be registered to a event source. Once registered, it will get notified when the event source generates events.

Event Types There are different event types and event listeners Mouse events are handled by mouse listeners Item selection events are handled by Item listeners and so forth Among the different types of events, the action event is the most common. Clicking on a button generates an action event Selecting a menu item generates an action event Action events are generated by action event sources and handled by action event listeners. There are different types of events. Some event sources generate only one type of events, while others generate three or four different types of events. For example, a button can generate an action event, a change event, and a item event. The most common type of event we are interested in processing for various types of GUI components is the action event.

Handling Action Events action event source actionPerformed action event listener JButton Button Handler addActionListener This code shows how we register an action event listener to a button. The object we register as an action listener must be an instance of a class that implements the ActionListener interface. The class must define a method named actionPerformed. This is the method executed in response to the generated action events. JButton button = new JButton("OK"); ButtonHandler handler = new ButtonHandler( ); button.addActionListener(handler);

What does an Event Handler require? It just looks for 3 pieces of code! First, in the declaration of the event handler class, one line of code must specify that the class implements either a listener interface or extends a class that implements a listener interface. public class DemoClass implements ActionListener {

What does an Event Handler require? Second, it looks for a line of code which registers an instance of the event handler class as a listener of one or more components because, as mentioned earlier, the object must be registered as an event listener. anyComponent.addActionListener(instanceOf DemoClass);

What does an Event Handler require? Third, the event handler must have a piece of code that implements the methods in the listener interface. public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

ActionListener Interface When we call the addActionListener method of an event source, we must pass an instance of a class that implements the ActionListener interface. The ActionListener interface includes one method named actionPerformed. A class that implements the ActionListener interface must therefore provide the method body of actionPerformed. Since actionPerformed is the method that will be called when an action event is generated, this is the place where we put a code we want to be executed in response to the generated events.

The ButtonHandler Class import javax.swing.*; import java.awt.*; import java.awt.event.*; class ButtonHandler implements ActionListener { . . . public void actionPerformed(ActionEvent event) { // code to be executed in response to the generated events } This actionPerformed method is programmed to change the title of the frame to 'You clicked OK' or 'You clicked Cancel'. The actionPerformed method accepts one parameter of type ActionEvent. The getSource method of ActionEvent returns the event source source object. Because the object can be of any type, we type cast it to JButton. The next two statements are necessary to get a frame object that contains this event source. Once we have a reference to this frame object, we call its setTitle method to change the frame's title. More discussion on this actionPerformed method is presented on page 397 of the textbook.

Container as Event Listener Instead of defining a separate event listener such as ButtonHandler, it is much more common to have an object that contains the event sources be a listener. Example: We make this frame a listener of the action events of the buttons it contains. event listener Because ActionListener is a Java interface and not a class, action event listener objects are not limited to instances of fixed classes. Any class can implement the ActionListener interface, so any object from a class that implements this interface can be an action event listener. This adds flexibility as this example illustrates. Instead of using a ButtonHandler object, we can make the frame object itself to be an action event listener. event source

JButtonFrameHandler (complete program-1) import javax.swing.*; import java.awt.*; import java.awt.event.*; class JButtonFrameHandler extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 200; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private JButton cancelButton; private JButton okButton;

JButtonFrameHandler (complete program-2) public JButtonFrameHandler() { Container contentPane = getContentPane( ); setSize (FRAME_WIDTH, FRAME_HEIGHT); setResizable (false); setTitle ("Program Ch14JButtonFrameHandler"); setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane.setLayout(new FlowLayout()); okButton = new JButton("OK"); contentPane.add(okButton); cancelButton = new JButton("CANCEL"); contentPane.add(cancelButton); //registering this frame as an action listener of the two buttons cancelButton.addActionListener(this); okButton.addActionListener(this); setDefaultCloseOperation( EXIT_ON_CLOSE ); }

JButtonFrameHandler (complete program-3) public void actionPerformed(ActionEvent event) { JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); this.setTitle("You clicked " + buttonText); } public static void main(String[] args) { JButtonFrameHandler frame = new JButtonFrameHandler(); frame.setVisible(true); } }

Example

JTextField

Intro to OOP with Java, C. Thomas Wu JTextField We use a JTextField object to accept a single line to text from a user. An action event is generated when the user presses the ENTER key. The getText method of JTextField is used to retrieve the text that the user entered. JTextField input = new JTextField( ); contentPane.add(input); The getText method is most commonly used inside the actionPerformed method of an action listener. input.addActionListener(eventListener); ©The McGraw-Hill Companies, Inc.

JTextField We want to write a program that displays the text of the clicked button (OK or CANCEL), or the text entered in the text field

import javax. swing. ; import java. awt. ; import java. awt. event import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14TextFrame1 extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 200; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private JButton cancelButton; private JButton okButton; private JTextField inputLine; public static void main(String[] args) { Ch14TextFrame1 frame = new Ch14TextFrame1(); frame.setVisible(true); } public Ch14TextFrame1() { Container contentPane; setSize (FRAME_WIDTH, FRAME_HEIGHT); setResizable (false); setTitle ("Program Ch14TextFrame1"); setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane( ); contentPane.setLayout(new FlowLayout());

JTextField inputLine = new JTextField(); inputLine.setColumns(22); inputLine.setFont(new Font("Courier", Font.PLAIN, 14)); contentPane.add(inputLine); inputLine.addActionListener(this); okButton = new JButton("OK"); contentPane.add(okButton); cancelButton = new JButton("CANCEL"); contentPane.add(cancelButton); //register this frame as an action listener of the two buttons cancelButton.addActionListener(this); okButton.addActionListener(this); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); }

public void actionPerformed(ActionEvent event) { if (event public void actionPerformed(ActionEvent event) { if (event.getSource() instanceof JButton) { JButton clickedButton = (JButton) event.getSource(); String buttonText = clickedButton.getText(); setTitle("You clicked " + buttonText); } else { //the event source is inputLine setTitle("You entered '" + inputLine.getText() + "'"); }

JLabel

Intro to OOP with Java, C. Thomas Wu JLabel We use a JLabel object to display a label. A label can be a text or an image. When creating an image label, we pass ImageIcon object instead of a string. JLabel textLabel = new JLabel(); textLabel.setText("Please enter your name"); textLabel.setSize(150,25); contentPane.add(textLabel); //we can also set the text at the time of object creation. JLabel Prompt = new JLabel ("Please enter your age"); ... A JLabel is strictly for displaying noneditable text or image. A JLabel object does not generate any events. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

Intro to OOP with Java, C. Thomas Wu JLabel with an Image JLabel imgLabel = new JLabel(new ImageIcon("cat.gif")); contentPane.add(imgLabel); JLabel (with a text) JLabel (with an image) JTextField The sample Ch7TextFrame2 class includes five GUI components: two JLabel objects, one JTextField object, and two JButton objects. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

JTextArea

Intro to OOP with Java, C. Thomas Wu JTextArea We use a JTextArea object to display or allow the user to enter multiple lines of text. The setText method assigns the text to a JTextArea, replacing the current content. The append method appends the text to the current text. JTextArea textArea = new JTextArea( ); . . . textArea.setText("Hello\n"); textArea.append("the lost "); textArea.append("world"); Notice how the append method works. If you want to place the text to be appended on a new line, you have ouput the newline control character \n at the appropriate point. Hello the lost world JTextArea ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ©The McGraw-Hill Companies, Inc.

JTextArea We want to create a frame with a JTextField and a JTextArea When the user enters a text in the JTextField, and then presses Enter or clicks the ADD button,the entered text will be appended to the JTextArea When the user clicks CLEAR the text in the JTextArea will be cleared JTextArea JTextField ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

import javax. swing. ; import java. awt. ; import java. awt. event import javax.swing.*; import java.awt.*; import java.awt.event.*; class Ch14TextFrame3 extends JFrame implements ActionListener { private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 250; private static final int FRAME_X_ORIGIN = 150; private static final int FRAME_Y_ORIGIN = 250; private static final String EMPTY_STRING = ""; private static final String NEWLINE = "\n"; private JButton clearButton; private JButton addButton; private JTextField inputLine; private JTextArea textArea; public static void main(String[] args) { Ch14TextFrame3 frame = new Ch14TextFrame3(); frame.setVisible(true); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

public Ch14TextFrame3() { Container contentPane; setSize (FRAME_WIDTH, FRAME_HEIGHT); setResizable (false); setTitle ("Program Ch14TextFrame3"); setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN); contentPane = getContentPane( ); contentPane.setLayout(new FlowLayout()); textArea = new JTextArea(); textArea.setColumns(22); textArea.setRows(8); textArea.setBorder(BorderFactory.createLineBorder(Color.red)); textArea.setEditable(false); contentPane.add(textArea); ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

inputLine = new JTextField(); inputLine. setColumns(22); contentPane inputLine = new JTextField(); inputLine.setColumns(22); contentPane.add(inputLine); inputLine.addActionListener(this); //create and place two buttons on the frame addButton = new JButton("ADD"); contentPane.add(addButton); addButton.addActionListener(this); clearButton = new JButton("CLEAR"); contentPane.add(clearButton); clearButton.addActionListener(this); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

JTextArea public void actionPerformed(ActionEvent event) { if (event.getSource() instanceof JButton) { JButton clickedButton = (JButton) event.getSource(); if (clickedButton == addButton) { addText(inputLine.getText()); } else { clearText( ); } } else { //the event source is inputLine addText(inputLine.getText()); } } //------------------------------------------------------- private void addText(String userInput) { textArea.append(userInput + NEWLINE); inputLine.setText(EMPTY_STRING); } //--------------------------------------------------------- private void clearText( ) { textArea.setText(EMPTY_STRING); inputLine.setText(EMPTY_STRING); } }