Java Tutorial/Swing Event/ActionListener

Материал из Java эксперт
Версия от 15:18, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

ActionEvent.getActionCommand()

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
class ButtonDemo implements ActionListener {
  JButton jbtnA = new JButton("Alpha");
  JButton jbtnB = new JButton("Beta");
  ButtonDemo() {
    JFrame jfrm = new JFrame("A Button Example");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(220, 90);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jbtnA.addActionListener(this);
    jbtnB.addActionListener(this);
    jfrm.add(jbtnA);
    jfrm.add(jbtnB);
    jfrm.setVisible(true);
  }
  public void actionPerformed(ActionEvent ae) {
    String ac = ae.getActionCommand();
    if (ac.equals("Alpha")) {
      if (jbtnB.isEnabled()) {
        System.out.println("Alpha pressed. Beta is disabled.");
        jbtnB.setEnabled(false);
      } else {
        System.out.println("Alpha pressed. Beta is enabled.");
        jbtnB.setEnabled(true);
      }
    } else if (ac.equals("Beta"))
      System.out.println("Beta pressed.");
  }
  public static void main(String args[]) {
    new ButtonDemo();
  }
}





Add action listener to JTextField

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test extends JFrame {
  JTextField text = new JTextField("Press Return", 40);
  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Text=" + text.getText());
      }
    });
    getContentPane().add(text, "Center");
    pack();
  }
  public static void main(String[] args) {
    new Test().setVisible(true);
  }
}





Check the event source in actionPerformed method

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JFrame implements ActionListener {
  private JButton button1 = new JButton("Click Me!");
  private int clickCount = 0;  
  public static void main(String[] args) {
    new MainClass();
  }
  public MainClass() {
    this.setSize(200, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("I"m Listening");
    JPanel panel1 = new JPanel();
    button1.addActionListener(this);
    panel1.add(button1);
    this.add(panel1);
    this.setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button1) {
      clickCount++;
      if (clickCount == 1)
        button1.setText("I"ve been clicked!");
      else
        button1.setText("I"ve been clicked" + clickCount + " times!");
    }
  }
}





ComboBox with ActionListener

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/* ComboBoxDemo2.java requires no other files. */
public class ComboBoxDemo2 extends JPanel implements ActionListener {
  static JFrame frame;
  JLabel result;
  String currentPattern;
  public ComboBoxDemo2() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    String[] patternExamples = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
        "yyyy.MM.dd G "at" hh:mm:ss z", "EEE, MMM d, ""yy", "h:mm a",
        "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa" };
    currentPattern = patternExamples[0];
    // Set up the UI for selecting a pattern.
    JLabel patternLabel1 = new JLabel("Enter the pattern string or");
    JLabel patternLabel2 = new JLabel("select one from the list:");
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setEditable(true);
    patternList.addActionListener(this);
    // Create the UI for displaying result.
    JLabel resultLabel = new JLabel("Current Date/Time", JLabel.LEADING); // ==
                                                                          // LEFT
    result = new JLabel(" ");
    result.setForeground(Color.black);
    result.setBorder(BorderFactory.createCompoundBorder(BorderFactory
        .createLineBorder(Color.black), BorderFactory.createEmptyBorder(5, 5,
        5, 5)));
    // Lay out everything.
    JPanel patternPanel = new JPanel();
    patternPanel.setLayout(new BoxLayout(patternPanel, BoxLayout.PAGE_AXIS));
    patternPanel.add(patternLabel1);
    patternPanel.add(patternLabel2);
    patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
    patternPanel.add(patternList);
    JPanel resultPanel = new JPanel(new GridLayout(0, 1));
    resultPanel.add(resultLabel);
    resultPanel.add(result);
    patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    add(patternPanel);
    add(Box.createRigidArea(new Dimension(0, 10)));
    add(resultPanel);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    reformat();
  } // constructor
  public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    String newSelection = (String) cb.getSelectedItem();
    currentPattern = newSelection;
    reformat();
  }
  /** Formats and displays today"s date. */
  public void reformat() {
    Date today = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(currentPattern);
    try {
      String dateString = formatter.format(today);
      result.setForeground(Color.black);
      result.setText(dateString);
    } catch (IllegalArgumentException iae) {
      result.setForeground(Color.red);
      result.setText("Error: " + iae.getMessage());
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ComboBoxDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    JComponent newContentPane = new ComboBoxDemo2();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





Get event source from ActionEvent

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MainClass extends JFrame {
  public static void main(String[] args) {
    new MainClass();
  }
  private JButton button1  = new JButton("Click Me!"), exitButton= new JButton("Exit");
  public MainClass() {
    this.setSize(275, 100);
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    ClickListener cl = new ClickListener();
    JPanel panel1 = new JPanel();
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        exitButton.doClick();
      }
    });
    button1.addActionListener(cl);
    panel1.add(button1);
    exitButton.addActionListener(cl);
    panel1.add(exitButton);
    this.add(panel1);
    this.setVisible(true);
  }
  private class ClickListener implements ActionListener {
    private int clickCount = 0;
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == button1) {
        clickCount++;
        if (clickCount == 1)
          button1.setText("clicked!");
        else
          button1.setText("clicked " + clickCount + " times!");
      } else if (e.getSource() == exitButton) {
        if (clickCount > 0)
          System.exit(0);
        else {
          JOptionPane.showMessageDialog(MainClass.this, "You must click at least once!",
              "Title", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  }
}





Handling an action listener

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    JButton source = (JButton) e.getSource();
    String buttonText = source.getText();
    JOptionPane.showMessageDialog(null, "You clicked" + buttonText);
  }
}
public class ActionListenerTest1 {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("ActionListener Test 1");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Register");
    button.addActionListener(new MyActionListener());
    frame.getContentPane().add(button);
    frame.pack();
    frame.setVisible(true);
  }
}





implements ActionListener and action class level variable

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MainClass extends JFrame {
  JTextField field = new JTextField();
  public static void main(String[] args) {
    MainClass st = new MainClass();
  }
  public SwingTest() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Press me");
    button.addActionListener(new ButtonListener());
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(button, BorderLayout.SOUTH);
    this.getContentPane().add(field, BorderLayout.NORTH);
    this.pack();
    this.setVisible(true);
  }
  class ButtonListener implements ActionListener {
    boolean toggle = true;
    public void actionPerformed(ActionEvent e) {
      if (toggle)
        field.setText("Simple");
      else
        field.setText("Sample");
      toggle = !toggle;
    }
  }
}





Use an Inner Class to handle the event

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JFrame {
  private JButton button1 = new JButton("Click Me!");
  public static void main(String[] args) {
    new MainClass();
  }
  public MainClass() {
    this.setSize(200, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("I"m Listening");
    ClickListener cl = new ClickListener();
    JPanel panel1 = new JPanel();
    
    button1.addActionListener(cl);
    panel1.add(button1);
    this.add(panel1);
    this.setVisible(true);
  }
  private class ClickListener implements ActionListener {
    private int clickCount = 0;
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == button1) {
        clickCount++;
        if (clickCount == 1)
          button1.setText("I"ve been clicked ");
        else
          button1.setText("I"ve been clicked!" + clickCount + " times!");
      }
    }
  }
}





Use one inner class to handle events from two buttons

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MainClass extends JFrame {
  public static void main(String[] args) {
    new MainClass();
  }
  private JButton button1  = new JButton("Click Me!"), exitButton= new JButton("Exit");
  public MainClass() {
    this.setSize(275, 100);
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    ClickListener cl = new ClickListener();
    JPanel panel1 = new JPanel();
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        exitButton.doClick();
      }
    });
    button1.addActionListener(cl);
    panel1.add(button1);
    exitButton.addActionListener(cl);
    panel1.add(exitButton);
    this.add(panel1);
    this.setVisible(true);
  }
  private class ClickListener implements ActionListener {
    private int clickCount = 0;
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == button1) {
        clickCount++;
        if (clickCount == 1)
          button1.setText("clicked!");
        else
          button1.setText("clicked " + clickCount + " times!");
      } else if (e.getSource() == exitButton) {
        if (clickCount > 0)
          System.exit(0);
        else {
          JOptionPane.showMessageDialog(MainClass.this, "You must click at least once!",
              "Title", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  }
}





Using an inner ActionListener class.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class InnerClass {
  class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      System.exit(0);
    }
  }
  public InnerClass() {
    JButton close = new JButton("Close");
    ButtonListener listener = new ButtonListener();
    close.addActionListener(listener);
    JFrame f = new JFrame();
    f.add(close);
    f.setSize(300, 200);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
  public static void main(String[] args) {
    new InnerClass();
  }
}