Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while."— Presentation transcript:

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

5 Seconda applicazione ButtonPanel Painter JFrame ActionListenerJPanel Button addActionListener 3

6 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 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 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/1/570863/slides/slide_8.jpg", "name": "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

9 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 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/1/570863/slides/slide_10.jpg", "name": "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

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

14 Ancora sugli Eventi Gestione degli eventi

15 Modello 1.1

16 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 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 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 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 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 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 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 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 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 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 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 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 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 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 30 Altri listeners action caret change document undoable edit item list selection window + Listeners speciali per componenti specifiche (treeNodeExpansion, ecc)


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

Similar presentations


Ads by Google