1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Introduction to Java 2 Programming
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
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.
Graphical User Interfaces (Part IV)
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
TCU CoSc Programming with Java Handling Events.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
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.
Event Handling.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
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.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
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.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Graphical User Interface Components: Part 1 Chapter 11.
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.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
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.
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
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.
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.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
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,
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.
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.
Lesson 28: More on the GUI button, frame and actions.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
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.
GUI Programming using Java - Event Handling
Lecture 15 Basic GUI programming
Modular Event Handling
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
Advanced User Interfaces
Graphical User Interface (pronounced "gooey")
CSE 114 – Computer Science I Event Programming
Event-driven programming for GUI
Introduction to Event Handling
Fondamenti di Java Introduzione alla costruzione di GUI
Presentation transcript:

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener Any property in a component changes such as the text on a label PropertyChangeListener

2 ActionListener public interface ActionListener extends EventListener The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. void actionPerformed(ActionEvent e) Invoked when an action occurs

3 ActionEvent ActionEvent extends AWTEvent A semantic event which indicates that a component- defined action occured. This high-level event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every every ActionListener object that registered to receive such events using the component's addActionListener method.

4 ActionEvent Method Summary StringString getActionCommand() Returns the command string associated with this action. getActionCommand int getModifiers() Returns the modifier keys held down during this action event. getModifiers long getWhen() Returns the timestamp of when this event occurred. getWhen StringString paramString() Returns a parameter string identifying this action event. paramString Methods Inherited … public Object getSource()Object Returns The object on which the Event initially occurred.

Seconda applicazione ButtonPanel Painter JFrame ActionListenerJPanel Button addActionListener 3

6 Esempio package actionlistener; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.JFrame; public class ButtonPanel extends JPanel { public ButtonPanel() { super(); JButton button1 = new JButton("Giallo"); JButton button2 = new JButton("Verde"); JButton button3 = new JButton("Rosso"); this.add(button1); this.add(button2); this.add(button3); Painter azioneGiallo = new Painter(Color.YELLOW,this); Painter azioneVerde = new Painter( Color.GREEN,this); Painter azioneRosso = new Painter(Color.RED,this); button1.addActionListener(azioneGiallo); button2.addActionListener(azioneVerde); button3.addActionListener(azioneRosso); }

7 Esempio - continua public static void main(String a[]) { JFrame f=new JFrame(); f.setContentPane(new ButtonPanel()); f.setSize(300,300); f.setVisible(true); } } class Painter implements ActionListener { private Color colore; private JPanel contenitore; public Painter(Color colore, JPanel contenitore) { this.colore = colore; this.contenitore=contenitore; } public void actionPerformed(ActionEvent actionEvent) { contenitore.setBackground(colore); }

8 Esempio 2 public class ButtonPanel extends JPanel { public ButtonPanel() { super(); Painter p=new Painter(this); String c[]={"Giallo","Verde","Rosso"}; for (int i=0;i<c.length;i++) { JButton b=new JButton(c[i]); this.add(b); b.addActionListener(p); // b.setActionCommand(c[i]); } public static void main(String a[]) { JFrame f=new JFrame(); f.setContentPane(new ButtonPanel()); f.setSize(300,300); f.setVisible(true); }

9 Esempio 2 - continua class Painter implements ActionListener { private JPanel contenitore; private Color colore; public Painter(JPanel contenitore) { this.contenitore=contenitore; } public void actionPerformed(ActionEvent actionEvent) { String s=((JButton)actionEvent.getSource()).getText(); //String s=actionEvent.getActionCommand(); if (s.equals("Giallo")) colore=Color.YELLOW; else if (s.equals("Rosso")) colore=Color.RED; else if (s.equals("Verde")) colore=Color.GREEN; contenitore.setBackground(colore); }

10 Esempio 3 public class ButtonPanel extends JPanel { public ButtonPanel() { super(); Painter p=new Painter(this); this.setLayout(null); String c[]={"Giallo","Verde","Rosso"}; for (int i=0;i<c.length;i++) { JButton b=new JButton(c[i]); b.setSize(100,50); b.setLocation(i*100,i*50); this.add(b); b.addActionListener(p); b.setActionCommand(c[i]); } NON CONSIGLIATO – LAYOUT NON LIQUIDO!

11 Compito Scrivere un applicazione contenente un bottone che quando viene premuto si sposta altrove nella finestra. Scrivere una applicazione contenente due bottoni: uno ingrandisce la dimensione della finestra, laltro la rimpicciolisce

12 Mouse events This low-level event is generated by a component object for: Mouse Events a mouse button is pressed a mouse button is released a mouse button is clicked (pressed and released) the mouse cursor enters the unobscured part of component's geometry the mouse cursor exits the unobscured part of component's geometry Mouse Motion Events the mouse is moved the mouse is dragged

13 Compito Scrivere un applicazione contenente un TextField il cui valore inizialmente è zero, e che viene incrementato di uno ogni volta che il bottone del mouse viene cliccato. Scrivere unapplicazione contenente un bottone che si posiziona dove viene cliccato il bottone del mouse. Se invece viene cliccato il bottone grafico, questo si riposiziona nella sua sede iniziale.

Ancora sugli Eventi Gestione degli eventi

Modello 1.1

16 multiListenerDemo package listenersdemo; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MultiListener extends JPanel implements ActionListener { JTextArea topTextArea; JTextArea bottomTextArea; JButton button1, button2; JLabel l = null; final static String newline = "\n"; public static void main(String[] args) { createAndShowGUI(); }

17 multiListenerDemo private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("MultiListener"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new MultiListener(); frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); }

18 multiListenerDemo public MultiListener() { super(new FlowLayout()); l = new JLabel("Cosa sento io:"); add(l); topTextArea = new JTextArea(); topTextArea.setEditable(false); JScrollPane topScrollPane = new JScrollPane(topTextArea); Dimension preferredSize = new Dimension(200, 75); topScrollPane.setPreferredSize(preferredSize); add(topScrollPane); l = new JLabel("Cosa sente la spia:"); add(l); bottomTextArea = new JTextArea(); bottomTextArea.setEditable(false);

19 multiListenerDemo JScrollPane bottomScrollPane = new JScrollPane(bottomTextArea); bottomScrollPane.setPreferredSize(preferredSize); add(bottomScrollPane); button1 = new JButton("Fra Martino campanaro"); add(button1); button2 = new JButton("Dormi tu?"); add(button2); button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Spia(bottomTextArea)); setPreferredSize(new Dimension(400, 300)); } public void actionPerformed(ActionEvent e) { topTextArea.append(e.getActionCommand() + newline); topTextArea.setCaretPosition(topTextArea.getDocument().getLe ngth()); }

20 multiListenerDemo class Spia implements ActionListener { JTextArea myTextArea; public Spia(JTextArea ta) { myTextArea = ta; } public void actionPerformed(ActionEvent e) { myTextArea.append(e.getActionCommand() + MultiListener.newline); myTextArea.setCaretPosition(myTextArea.getDocument().getLe ngth()); }

21 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly. Because all drawing and event- listening methods are executed in the same thread, a slow event- listener method can make the program seem unresponsive and slow to repaint itself. You might choose to implement separate classes for different kinds of event listeners. This can be an easy architecture to maintain, but many classes can also mean reduced performance. When designing your program, you might want to implement your event listeners in a class that is not public, but somewhere more hidden. A private implementation is a more secure implementation.

22 Low-Level Events and Semantic Events Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible. For example, listening for action events on buttons, rather than mouse events, means that the button will react appropriately when the user tries to activate the button using a keyboard alternative or a look-and-feel-specific gesture.

23 Listeners/Adapters public class MyClass implements MouseListener {... someObject.addMouseListener(this);... /* Empty method definition. */ public void mousePressed(MouseEvent e) { } /* Empty method definition. */ public void mouseReleased(MouseEvent e) { } /* Empty method definition. */ public void mouseEntered(MouseEvent e) { } /* Empty method definition. */ public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {...//Event listener implementation goes here... } }

24 Listeners/Adapters /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class MyClass extends MouseAdapter {... someObject.addMouseListener(this);... public void mouseClicked(MouseEvent e) { //Event listener implementation goes here... } }

25 Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MyAdapter());... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } }

26 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter () { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } ); … }

27 Inner classes An instance of InnerClass can exist only within an instance of EnclosingClass and it has direct access to the instance variables and methods of its enclosing instance.

28 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } } });... }

29 Listeners supported by all Swing components component listener Listens for changes in the component's size, position, or visibility. focus listener Listens for whether the component gained or lost the ability to receive keyboard input. key listener Listens for key presses; key events are fired only by the component that has the current keyboard focus. mouse listener Listens for mouse clicks and mouse movement into or out of the component's drawing area. mouse-motion listener Listens for changes in the cursor's position over the component. mouse-wheel listenermouse-wheel listener (introduced in 1.4) Listens for mouse wheel movement over the component.

30 Altri listeners action caret change document undoable edit item list selection window + Listeners speciali per componenti specifiche (treeNodeExpansion, ecc)