Java/Event/Swing Action

Материал из Java эксперт
Перейти к: навигация, поиск

Demonstrate a listener being reused

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. All rights
 * reserved. Software written by Ian F. Darwin and others. $Id: LICENSE,v 1.8
 * 2004/02/09 03:33:38 ian Exp $
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer. 2. 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.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee cup"
 * logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Button;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ListenerReuse extends Frame {
  public ListenerReuse() {
    Button b = new Button("Save");
    add(b);
    MenuBar mb = new MenuBar();
    setMenuBar(mb);
    Menu fm = new Menu("File");
    mb.add(fm);
    MenuItem mi = new MenuItem("Save");
    fm.add(mi);
    // Construct the ActionListener, and keep a reference to it.
    ActionListener saver = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Saving your file...");
        // In real life we would call the doSave() method
        // in the main class, something like this:
        // mainProg.doSave();
      }
    };
    // Register the actionListener with the Button
    b.addActionListener(saver);
    // And now register the same actionListener with the MenuItem
    mi.addActionListener(saver);
    pack();
  }
  /** Main just calls the above */
  public static void main(String[] a) {
    ListenerReuse lr = new ListenerReuse();
    lr.setVisible(true);
  }
}





Derive a class from a component and implement an action listener inside the class.

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





How to have multiple listeners

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 * Demo I wrote in response to a student request for how to have multiple
 * listeners (Bobs) that are already on-screen added as listeners to a
 * newly-created pushbutton (Fred).
 */
public class MultiListeners {
  public static void main(String[] args) {
    Bob b1 = new Bob();
    b1.setVisible(true);
    Bob b2 = new Bob();
    b2.setVisible(true);
    ActionListener[] bobs = { b1, b2 };
    Fred f1 = new Fred(bobs);
    f1.setVisible(true);
  }
}
class Fred extends JFrame {
  JButton okbutton = new JButton("OK");
  public Fred(ActionListener[] bobs) {
    getContentPane().add(okbutton);
    for (int i = 0; i < bobs.length; i++) {
      okbutton.addActionListener(bobs[i]);
    }
  }
}
class Bob extends JFrame implements ActionListener {
  protected JLabel statusLabel = new JLabel("     ");
  public Bob() {
    getContentPane().add(statusLabel);
  }
  public void actionPerformed(ActionEvent e) {
    statusLabel.setText("OK");
  }
}





Keymap and KeyStroke Demo

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;
public class DefaultSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = frame.getContentPane();
    JTextField textField = new JTextField();
    content.add(textField, BorderLayout.NORTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out
            .println(actionEvent.getActionCommand() + " selected");
      }
    };
    JPanel panel = new JPanel();
    JButton defaultButton = new JButton("Default Button");
    defaultButton.addActionListener(actionListener);
    panel.add(defaultButton);
    JButton otherButton = new JButton("Other Button");
    otherButton.addActionListener(actionListener);
    panel.add(otherButton);
    content.add(panel, BorderLayout.SOUTH);
    Keymap keymap = textField.getKeymap();
    KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0,
        false);
    keymap.removeKeyStrokeBinding(keystroke);
    frame.getRootPane().setDefaultButton(defaultButton);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Use Action class

 
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ColorAction extends AbstractAction {
  public ColorAction(String name, Icon icon, Color c, Component comp) {
    putValue(Action.NAME, name);
    putValue(Action.SMALL_ICON, icon);
    putValue("Color", c);
    target = comp;
  }
  public void actionPerformed(ActionEvent evt) {
    Color c = (Color) getValue("Color");
    target.setBackground(c);
    target.repaint();
  }
  private Component target;
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("SeparateGUITest");
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JPanel panel = new JPanel();
    Action blueAction = new ColorAction("Blue", new ImageIcon(
        "blue-ball.gif"), Color.blue, panel);
    Action yellowAction = new ColorAction("Yellow", new ImageIcon(
        "yellow-ball.gif"), Color.yellow, panel);
    Action redAction = new ColorAction("Red",
        new ImageIcon("red-ball.gif"), Color.red, panel);
    panel.add(new JButton(yellowAction));
    panel.add(new JButton(blueAction));
    panel.add(new JButton(redAction));
    panel.registerKeyboardAction(yellowAction, KeyStroke.getKeyStroke(
        KeyEvent.VK_Y, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
    panel.registerKeyboardAction(blueAction, KeyStroke.getKeyStroke(
        KeyEvent.VK_B, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
    panel.registerKeyboardAction(redAction, KeyStroke.getKeyStroke(
        KeyEvent.VK_R, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
    Container contentPane = frame.getContentPane();
    contentPane.add(panel);
    JMenu m = new JMenu("Color");
    m.add(yellowAction);
    m.add(blueAction);
    m.add(redAction);
    JMenuBar mbar = new JMenuBar();
    mbar.add(m);
    frame.setJMenuBar(mbar);
    frame.show();
  }
}





You can change event behavior dynamically

 
// : c14:DynamicEvents.java
// You can change event behavior dynamically.
// Also shows multiple actions for an event.
// <applet code=DynamicEvents
// width=250 height=400></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class DynamicEvents extends JApplet {
  private java.util.List list = new ArrayList();
  private int i = 0;
  private JButton b1 = new JButton("Button1"), b2 = new JButton("Button2");
  private JTextArea txt = new JTextArea();
  class B implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      txt.append("A button was pressed\n");
    }
  }
  class CountListener implements ActionListener {
    private int index;
    public CountListener(int i) {
      index = i;
    }
    public void actionPerformed(ActionEvent e) {
      txt.append("Counted Listener " + index + "\n");
    }
  }
  class B1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      txt.append("Button 1 pressed\n");
      ActionListener a = new CountListener(i++);
      list.add(a);
      b2.addActionListener(a);
    }
  }
  class B2 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      txt.append("Button2 pressed\n");
      int end = list.size() - 1;
      if (end >= 0) {
        b2.removeActionListener((ActionListener) list.get(end));
        list.remove(end);
      }
    }
  }
  public void init() {
    Container cp = getContentPane();
    b1.addActionListener(new B());
    b1.addActionListener(new B1());
    b2.addActionListener(new B());
    b2.addActionListener(new B2());
    JPanel p = new JPanel();
    p.add(b1);
    p.add(b2);
    cp.add(BorderLayout.NORTH, p);
    cp.add(new JScrollPane(txt));
  }
  public static void main(String[] args) {
    run(new DynamicEvents(), 250, 400);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~