swingactions.java~7~

来自「《深入浅出设计模式》的完整源代码」· JAVA~7~ 代码 · 共 77 行

JAVA~7~
77
字号
package swingaction;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingActions extends JFrame{
  private JToolBar tb;
  private JTextArea ta;
  private JMenu fileMenu;
  private JMenu testMenu;
  private Action openAction;
  private Action testAction;
  private Action closeAction;
  public SwingActions () {
    super ("SwingActions");
    setupGUI ();
  }

  private void setupGUI () {
//Create the toolbar and menu.
    tb = new JToolBar ();
    fileMenu = new JMenu ("File");
    testMenu=new JMenu("Test");

//Create the text area used for output.
    ta = new JTextArea (5, 30);
    JScrollPane scrollPane = new JScrollPane (ta);
//Layout the content pane.
    JPanel contentPane = new JPanel ();
    contentPane.setLayout (new BorderLayout ());
    contentPane.setPreferredSize (new Dimension (400, 150));
    contentPane.add (tb, BorderLayout.NORTH);
    contentPane.add (scrollPane, BorderLayout.CENTER);
    setContentPane (contentPane);
//Set up the menu bar.
    JMenuBar mb = new JMenuBar ();
    mb.add (fileMenu);
    mb.add(testMenu);
    setJMenuBar (mb);
// Create an action for "Open".
    ImageIcon openIcon = new ImageIcon ("open.gif");
    openAction = new AbstractAction ("Open", openIcon) {
      public void actionPerformed (ActionEvent e) {
        ta.append ("Open action from " + e.getActionCommand () + "\n");
      }};
    testAction=new AbstractAction("testItem",openIcon){
      public void actionPerformed(ActionEvent e)
      {
        ta.append("i just want to test it");

      }
    };
// Use the action to add a button to the toolbar.
    JButton openButton = tb.add (openAction);
    openButton.setText ("");
    openButton.setActionCommand ("Open Button");
    openButton.setToolTipText ("This is the open button");
// Use the action to add a menu item to the file menu.
    JMenuItem openMenuItem = fileMenu.add (openAction);
    JMenuItem test=testMenu.add(testAction);
    openMenuItem.setIcon (null);
    openMenuItem.setActionCommand ("Open Menu Item");
// Create an action for "Close" and use the action to add
// a button to the toolbar and a menu item to the menu.
// Code NOT shown - similar to "open" code above.
  }

  public static void main (String[] args) {
    SwingActions frame = new SwingActions ();
    frame.pack ();
    frame.setVisible (true);
  }
}



⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?