1 event listeners some events and their associated event listeners act that results in the...

30
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the Event Listener 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 MouseMotionListene r Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListe

Upload: alexandra-mcgrath

Post on 26-Mar-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

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

1

Event Listeners

Some Events and Their Associated Event Listeners

Act that Results in the Event Listener 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

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

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

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

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.

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

4

ActionEvent

Method Summary String getActionCommand()

     Returns the command string associated with this action. int getModifiers()

     Returns the modifier keys held down during this action event. 

long getWhen()      Returns the timestamp of when this event occurred. 

String paramString()      Returns a parameter string identifying this action event. 

Methods Inherited …public Object getSource()

Returns The object on which the Event initially occurred.

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

Seconda applicazione

ButtonPanel PainterJFrame

ActionListenerJPanel

ButtonaddActionListener

3

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

6

Esempiopackage 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);   }

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

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); } }

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

8

Esempio 2public 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); }}

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

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); } }

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

10

Esempio 3public 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!

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

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, l’altro la rimpicciolisce

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

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

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

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 un’applicazione 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.

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

Ancora sugli Eventi

Gestione deglieventi

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

Modello 1.1

Event isgenerated for a

component

Listener executessuitable method

Component getsthe event

Event isconsumed

Componentpasses the Event

to Listener

Component has notregistered for that

event classEvent is discarded

Component has registered for that event class

Component

Listener interface

AWTEvent

x

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

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(); }

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

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); }

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

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);

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

19

multiListenerDemoJScrollPane 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().getLength());

}}

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

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().getLength());

}}

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

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.

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

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.

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

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... } }

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

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 ... }

}

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

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... } } }

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

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... } } ); …}

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

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.

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

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... }

}});

... }

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

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 listener (introduced in 1.4)

Listens for mouse wheel movement over the component.

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

30

Altri listeners

action caret change document

undoable edit item listselection window+ Listeners speciali per componenti specifiche

(treeNodeExpansion, ecc)