1 / 30

ActionListener Interface in Java GUI Programming

Learn about ActionListener interface for receiving action events in Java GUI programming. Example code explains how to handle and process action events effectively.

dorismccain
Download Presentation

ActionListener Interface in Java GUI Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Event Listeners

  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 • StringgetActionCommand() 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.  • StringparamString() Returns a parameter string identifying this action event.  • Methods Inherited • … • public ObjectgetSource() Returns The object on which the Event initially occurred.

  5. Seconda applicazione JPanel ActionListener Painter ButtonPanel JFrame 3 addActionListener Button

  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.

  14. Ancora sugli Eventi • Gestione • degli • eventi

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

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

  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 listener(introduced in 1.4) • Listens for mouse wheel movement over the component.

  30. Altri listeners • action • caret • change • documentundoable edit • item • listselection • window • + Listeners speciali per componenti specifiche (treeNodeExpansion, ecc)

More Related