swingactions.java~3~
来自「《深入浅出设计模式》的完整源代码」· JAVA~3~ 代码 · 共 64 行
JAVA~3~
64 行
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 Action openAction;
private Action closeAction;
public SwingActions () {
super ("SwingActions");
setupGUI ();
}
private void setupGUI () {
//Create the toolbar and menu.
tb = new JToolBar ();
fileMenu = new JMenu ("File");
//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);
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");
}};
// 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);
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 + -
显示快捷键?