Event-Driven Programming

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University Mouse Events + Chapter 17: Applets.
Advertisements

Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Gui Interfaces a la Swing Up to speed with Swing by Steven Gutz is a good source It don’t mean a thing if it ain’t got that swing Duke Ellington.
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.
For IST410 Students only Events-1 Event Handling.
Unit 111 Event-Driven Programming Listener or Event handler Example: Handling Button Events Example: Handling Mouse Events Example: Handling Keyboard Events.
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
Slides prepared by Rose Williams, Binghamton University Chapter 18 Applets.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Lecture 19 Graphics User Interfaces (GUIs)
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Intermediate Java1 An example that uses inner classes Week Four Continued.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
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.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
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.
GUI programming Graphical user interface-based programming.
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.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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.
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.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Object Oriented Programming.  Interface  Event Handling.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
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.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
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.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as 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.
Event Handling and Listeners in SWING The practice of event handling.
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.
Event Handling CS 21a: Introduction to Computing I First Semester,
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 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Chapter 14 Applets. Applets: Introduction Java programs are divided into two main categories, applets and applications An application is an ordinary Java.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Chapter 14 Event-Driven Programming
Java Applet What is a Java Applet? How is applet compiled?
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Web Design & Development Lecture 11
Event Handling Chapter 2 Objectives
Event-driven programming for GUI
Graphical user interface-based programming
Chapter 16 Event-Driven Programming
Presentation transcript:

Event-Driven Programming Learning Outcomes Extend the example programs to write more interesting GUI Use nested classes and adapter classes to write medium-sized applications. Example 1: Handling Button Events Example 2: Handling Mouse Events Example 3: Handling Keyboard Events Self-check Exercise 1 Adapter Classes Example 4: Handling Window Events Example 5: Handling Text Field Events Self-check Exercise 2 Exercises Unit 12

Handling Button Events This example builds on Example 2 of the preceding section. Notice that when the button is pushed in that example, nothing happens. We will add some code to respond to the button pushes. When the mouse is pushed it generates and ActionEvent. Thus, we will be implementing the corresponding ActionListener interface. ActionListener consists of the method: Unit 12

Example 1: Button Events 1 import java.awt.*; 2 import java.awt.event.*; 3 class ButtonEventTest extends AddingComponents 4 implements ActionListener{ 5 private int sum; 6 public ButtonEventTest() { 7 button.addActionListener(this); 8 } 9 public void actionPerformed(ActionEvent ae) { 10 sum += 1; 11 textField.setText(sum+""); 12 Toolkit.getDefaultToolkit().beep(); 13 } 14 public static void main(String args []) { 15 new ButtonEventTest(); 16 } 17 } Unit 12

Handling Mouse Events This example illustrates how mouse events can be responded to. It also shows how a single listener can register with many sources. The event listener in this case will implement the MouseListener interface. MouseListener consists of five methods: The program is given in the following page. Unit 12

Example 2: Mouse Events 1 import java.awt.*; import java.awt.event.*; 2 public class MouseEventTest extends ButtonEventTest{ 3 public MouseEventTest(){ 4 class LightUpListener extends MouseAdapter { 5 public void mouseEntered(MouseEvent e) { 6 Component c = (Component)e.getSource(); 7 c.setBackground(Color.green); 8 } 9 public void mouseExited(MouseEvent e) { 10 Component c = (Component)e.getSource(); 11 c.setBackground(Color.red); 12 } 13 } 14 MouseListener listener = new LightUpListener(); 15 button.addMouseListener(listener); 16 textField.addMouseListener(listener); 17 cp.addMouseListener(listener); 18 } 19 public static void main(String[] args) { 20 new MouseEventTest(); 21 } 22 } Unit 12

Handling Keyboard Events This example illustrates how keyboard events can be responded to. To receive KeyEvent, a component must have keyboard focus. We will be implementing the KeyListener interface. KeyListener consists of three methods: Notice that when you press a key, at least two events are generated. Unit 12

Example 3: Keyboard Events 1 import java.awt.*; import java.awt.event.*; 2 import javax.swing.JApplet; 3 public class KeyEventTest extends JApplet implements KeyListener{ 4 private String msg = ""; 5 private int startX = 10, startY = 10; 6 public void keyPressed(KeyEvent ke){ 7 showStatus("Key Down"); 8 } 9 public void keyReleased(KeyEvent ke){showStatus("Key Up"); } 10 public void keyTyped(KeyEvent ke){ 11 msg += ke.getKeyChar(); 12 repaint(); 13 } 14 public void init(){ 15 requestFocus(); 16 addKeyListener(this); 17 } 18 public void paint(Graphics g){ 19 g.drawString(msg,startX,startY); 20 } 21 } Unit 12

Introduction to Adapter Classes From previous examples, listener interfaces can have several methods. A particular listener may not be interested in all the methods. Nevertheless, the listener must implement all methods in the interface. Java provides adapter classes for implementing handlers selectively. Adapter classes provide empty implementations for the handlers. Most listener interfaces with two or more methods have matching adapter classes. Unit 12

Handling Window Events This example shows how window events can be handled. The listener should implement the WindowListener interface. WindowListener consists of seven methods: We will extend the corresponding WindowAdapter in this example. Unit 12

Example 4: Window Events 1 import javax.swing.*;import java.awt.event.*; 2 class WindowEventTest extends JFrame{ 3 private String msg = "Are you sure you want to Quit Window?"; 4 public WindowEventTest() { 5 super("Window Event Test"); setSize(300,300); 6 addWindowListener(new WindowAdapter(){ 7 public void windowClosing(WindowEvent we) { 8 WindowEventTest obj = WindowEventTest.this; 9 int result = JOptionPane.showConfirmDialog(obj, msg); 10 if (result == JOptionPane.YES_OPTION) 11 System.exit(0); 12 else { 13 int keepOpen = WindowConstants.DO_NOTHING_ON_CLOSE; 14 setDefaultCloseOperation(keepOpen); 15 } 16 }}); 17 } 18 public static void main(String args [] ) { 19 WindowEventTest wt = new WindowEventTest(); 20 wt.setVisible(true); 21 } 22 } Unit 12

Handling Text Field Events This example shows how texfield events are generated and handled. It also illustrates the use of multiple handlers. Two text fields are shown handling an ActionEvent in different ways. The program implements Celcius to Fahrenheit temperature conversions. You enter a temperature value in one text field and get the equivalent in the other. The complete program follows in the next page. Unit 12

Example 5: Text Field Events 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TextFieldEventTest extends JFrame{ 5 JTextField celcius = new JTextField(10); 6 JTextField fahrenheit = new JTextField(10); 7 Container c = getContentPane(); 8 TextFieldEventTest(){ 9 c.setLayout(new FlowLayout()); 10 c.add(new JLabel("Celcius")); 11 c.add(celcius); 12 celcius.addActionListener(new ActionListener() { 13 public void actionPerformed(ActionEvent ae){ 14 String cString = celcius.getText(); 15 double cValue = Double.parseDouble(cString.trim()); 16 double fValue = cValue*9.0/5.0+32.0; 17 fahrenheit.setText((int)fValue+""); 18 } }); // code continues next page Unit 12

Text Field Events – Cont’d 20 c.add(new JLabel("Fahrenheit")); 21 c.add(fahrenheit); 22 fahrenheit.addActionListener(new ActionListener() { 23 public void actionPerformed(ActionEvent ae){ 24 String fString = fahrenheit.getText(); 25 double fValue = Double.parseDouble(fString.trim()); 26 double cValue = (fValue-32.0)*5.0/9.0; 27 celcius.setText((int)cValue+""); 28 } 29 }); 30 } // end of constructor 31 public static void main(String [] args){ 32 TextFieldEventTest t = new TextFieldEventTest(); 33 t.pack(); 34 t.show(); 35 } 36 } Unit 12

Review Exercises Extend Example 1 by adding a Reset Total button. When the Reset Total button is pushed, the running total should be reset to zero. Modify the program in Example 2 to work as a stand-alone application. Modify the program in Example 3 to display its output on the application’s JFrame window. Modify the program in Example 4 to use an anonymous inner class to implement the windowClosing() handler method. Extend Example 5 to validate the data entered in both text fields to avoid the spurious exceptions currently raised when invalid characters are included in the input. Unit 12

Review Exercises (cont’d) A student has written a working applet. Write a step-by-step procedure that guides the student to make his applet work as an application also. Consider the program in Example 1. Write down all the events generated from the time the frame is displayed up to the time the user pushes the PushMe button. You may restrict your answer to the events covered in this section. Unit 12