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 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 componentdefined 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 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. Seconda applicazione JFrame JPanel ActionListener ButtonPanel Painter 3 Button addActionListener 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, l’altro 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 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. Ancora sugli Eventi Gestione degli eventi Modello 1.1 Listener interface Component x AWTEvent Event is generated for a component Component has not registered for that event class Event is discarded Component has registered for that event class Component gets the event Event is consumed Component passes the Event to Listener Listener executes suitable method 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 eventlistening methods are executed in the same thread, a slow eventlistener 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 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)