Java基础之处理事件——添加菜单图标(Sketcher 8 with toolbar buttons and menu icons)

控制台程序。

要为菜单项添加图标以补充工具栏图标,只需要在创建菜单项的Action对象中添加IconImage对象,作为SMALL_ICON键的值即可。

 1 // Defines application wide constants
 2 package Constants;
 3 import java.awt.Color;
 4 import javax.swing.*;
 5 
 6 public class SketcherConstants {
 7   // Path for images
 8   public final static String imagePath = "E:/JavaProject/BeginningJava/Images/";
 9 
10   // Toolbar icons
11   public final static Icon NEW24 = new ImageIcon(imagePath + "New24.gif");
12   public final static Icon OPEN24 = new ImageIcon(imagePath + "Open24.gif");
13   public final static Icon SAVE24 = new ImageIcon(imagePath + "Save24.gif");
14   public final static Icon SAVEAS24 = new ImageIcon(imagePath + "SaveAs24.gif");
15   public final static Icon PRINT24 = new ImageIcon(imagePath + "Print24.gif");
16 
17   public final static Icon LINE24 = new ImageIcon(imagePath + "Line24.gif");
18   public final static Icon RECTANGLE24 = new ImageIcon(imagePath + "Rectangle24.gif");
19   public final static Icon CIRCLE24 = new ImageIcon(imagePath + "Circle24.gif");
20   public final static Icon CURVE24 = new ImageIcon(imagePath + "Curve24.gif");
21 
22   public final static Icon RED24 = new ImageIcon(imagePath + "Red24.gif");
23   public final static Icon GREEN24 = new ImageIcon(imagePath + "Green24.gif");
24   public final static Icon BLUE24 = new ImageIcon(imagePath + "Blue24.gif");
25   public final static Icon YELLOW24 = new ImageIcon(imagePath + "Yellow24.gif");
26 
27   // Menu item icons
28   public final static Icon NEW16 = new ImageIcon(imagePath + "new16.gif");
29   public final static Icon OPEN16 = new ImageIcon(imagePath + "Open16.gif");
30   public final static Icon SAVE16 = new ImageIcon(imagePath + "Save16.gif");
31   public final static Icon SAVEAS16 = new ImageIcon(imagePath + "SaveAs16.gif");
32   public final static Icon PRINT16 = new ImageIcon(imagePath + "print16.gif");
33 
34   public final static Icon LINE16 = new ImageIcon(imagePath + "Line16.gif");
35   public final static Icon RECTANGLE16 = new ImageIcon(imagePath + "Rectangle16.gif");
36   public final static Icon CIRCLE16 = new ImageIcon(imagePath + "Circle16.gif");
37   public final static Icon CURVE16 = new ImageIcon(imagePath + "Curve16.gif");
38 
39   public final static Icon RED16 = new ImageIcon(imagePath + "Red16.gif");
40   public final static Icon GREEN16 = new ImageIcon(imagePath + "Green16.gif");
41   public final static Icon BLUE16 = new ImageIcon(imagePath + "Blue16.gif");
42   public final static Icon YELLOW16 = new ImageIcon(imagePath + "Yellow16.gif");
43 
44   // Element type definitions
45   public final static int LINE      = 101;
46   public final static int RECTANGLE = 102;
47   public final static int CIRCLE    = 103;
48   public final static int CURVE     = 104;
49 
50   // Initial conditions
51   public final static int DEFAULT_ELEMENT_TYPE = LINE;
52   public final static Color DEFAULT_ELEMENT_COLOR = Color.BLUE;
53 }
  1 // Frame for the Sketcher application
  2 import javax.swing.*;
  3 import javax.swing.border.*;
  4 import java.awt.event.*;
  5 import java.awt.*;
  6 
  7 import static java.awt.event.InputEvent.*;
  8 import static java.awt.AWTEvent.*;
  9 import static java.awt.Color.*;
 10 import static Constants.SketcherConstants.*;
 11 import static javax.swing.Action.*;
 12 
 13 @SuppressWarnings("serial")
 14 public class SketcherFrame extends JFrame {
 15   // Constructor
 16   public SketcherFrame(String title) {
 17     setTitle(title);                                                   // Set the window title
 18     setJMenuBar(menuBar);                                              // Add the menu bar to the window
 19     setDefaultCloseOperation(EXIT_ON_CLOSE);                           // Default is exit the application
 20 
 21     createFileMenu();                                                  // Create the File menu
 22     createElementMenu();                                               // Create the element menu
 23     createColorMenu();                                                 // Create the element menu
 24     createToolbar();
 25     toolBar.setRollover(true);
 26     getContentPane().add(toolBar, BorderLayout.NORTH);
 27   }
 28 
 29   // Create File menu item actions
 30   private void createFileMenuActions() {
 31     newAction = new FileAction("New", 'N', CTRL_DOWN_MASK);
 32     openAction = new FileAction("Open", 'O', CTRL_DOWN_MASK);
 33     closeAction = new FileAction("Close");
 34     saveAction = new FileAction("Save", 'S', CTRL_DOWN_MASK);
 35     saveAsAction = new FileAction("Save As...");
 36     printAction = new FileAction("Print", 'P', CTRL_DOWN_MASK);
 37     exitAction = new FileAction("Exit", 'X', CTRL_DOWN_MASK);
 38 
 39     // Initialize the array
 40     FileAction[] actions = {openAction, closeAction, saveAction, saveAsAction, printAction, exitAction};
 41     fileActions = actions;
 42 
 43     // Add toolbar icons
 44     newAction.putValue(LARGE_ICON_KEY, NEW24);
 45     openAction.putValue(LARGE_ICON_KEY, OPEN24);
 46     saveAction.putValue(LARGE_ICON_KEY, SAVE24);
 47     saveAsAction.putValue(LARGE_ICON_KEY, SAVEAS24);
 48     printAction.putValue(LARGE_ICON_KEY, PRINT24);
 49 
 50     // Add menu item icons
 51     newAction.putValue(SMALL_ICON, NEW16);
 52     openAction.putValue(SMALL_ICON, OPEN16);
 53     saveAction.putValue(SMALL_ICON, SAVE16);
 54     saveAsAction.putValue(SMALL_ICON,SAVEAS16);
 55     printAction.putValue(SMALL_ICON, PRINT16);
 56   }
 57 
 58   // Create the File menu
 59   private void createFileMenu() {
 60     JMenu fileMenu = new JMenu("File");                                // Create File menu
 61     fileMenu.setMnemonic('F');                                         // Create shortcut
 62     createFileMenuActions();                                           // Create Actions for File menu item
 63 
 64     // Construct the file drop-down menu
 65     fileMenu.add(newAction);                                           // New Sketch menu item
 66     fileMenu.add(openAction);                                          // Open sketch menu item
 67     fileMenu.add(closeAction);                                         // Close sketch menu item
 68     fileMenu.addSeparator();                                           // Add separator
 69     fileMenu.add(saveAction);                                          // Save sketch to file
 70     fileMenu.add(saveAsAction);                                        // Save As menu item
 71     fileMenu.addSeparator();                                           // Add separator
 72     fileMenu.add(printAction);                                         // Print sketch menu item
 73     fileMenu.addSeparator();                                           // Add separator
 74     fileMenu.add(exitAction);                                          // Print sketch menu item
 75     menuBar.add(fileMenu);                                             // Add the file menu
 76   }
 77 
 78   // Create Element  menu actions
 79   private void createElementTypeActions() {
 80     lineAction = new TypeAction("Line", LINE, 'L', CTRL_DOWN_MASK);
 81     rectangleAction = new TypeAction("Rectangle", RECTANGLE, 'R', CTRL_DOWN_MASK);
 82     circleAction =  new TypeAction("Circle", CIRCLE,'C', CTRL_DOWN_MASK);
 83     curveAction = new TypeAction("Curve", CURVE,'U', CTRL_DOWN_MASK);
 84 
 85     // Initialize the array
 86     TypeAction[] actions = {lineAction, rectangleAction, circleAction, curveAction};
 87     typeActions = actions;
 88 
 89     // Add toolbar icons
 90     lineAction.putValue(LARGE_ICON_KEY, LINE24);
 91     rectangleAction.putValue(LARGE_ICON_KEY, RECTANGLE24);
 92     circleAction.putValue(LARGE_ICON_KEY, CIRCLE24);
 93     curveAction.putValue(LARGE_ICON_KEY, CURVE24);
 94 
 95     // Add menu item icons
 96     lineAction.putValue(SMALL_ICON, LINE16);
 97     rectangleAction.putValue(SMALL_ICON, RECTANGLE16);
 98     circleAction.putValue(SMALL_ICON, CIRCLE16);
 99     curveAction.putValue(SMALL_ICON, CURVE16);
100   }
101 
102   // Create the Elements menu
103   private void createElementMenu() {
104     createElementTypeActions();
105     elementMenu = new JMenu("Elements");                               // Create Elements menu
106     elementMenu.setMnemonic('E');                                      // Create shortcut
107     createRadioButtonDropDown(elementMenu, typeActions, lineAction);
108     menuBar.add(elementMenu);                                          // Add the element menu
109   }
110 
111   // Create Color menu actions
112   private void createElementColorActions() {
113     redAction = new ColorAction("Red", RED, 'R', CTRL_DOWN_MASK|ALT_DOWN_MASK);
114     yellowAction = new ColorAction("Yellow", YELLOW, 'Y', CTRL_DOWN_MASK|ALT_DOWN_MASK);
115     greenAction = new ColorAction("Green", GREEN, 'G', CTRL_DOWN_MASK|ALT_DOWN_MASK);
116     blueAction = new ColorAction("Blue", BLUE, 'B', CTRL_DOWN_MASK|ALT_DOWN_MASK);
117 
118     // Initialize the array
119     ColorAction[] actions = {redAction, greenAction, blueAction, yellowAction};
120     colorActions = actions;
121 
122     // Add toolbar icons
123     redAction.putValue(LARGE_ICON_KEY, RED24);
124     greenAction.putValue(LARGE_ICON_KEY, GREEN24);
125     blueAction.putValue(LARGE_ICON_KEY, BLUE24);
126     yellowAction.putValue(LARGE_ICON_KEY, YELLOW24);
127 
128     // Add menu item icons
129     redAction.putValue(SMALL_ICON, RED16);
130     greenAction.putValue(SMALL_ICON, GREEN16);
131     blueAction.putValue(SMALL_ICON, BLUE16);
132     yellowAction.putValue(SMALL_ICON, YELLOW16);
133   }
134 
135   // Create the Color menu
136   private void createColorMenu() {
137     createElementColorActions();
138     colorMenu = new JMenu("Color");                                    // Create Elements menu
139     colorMenu.setMnemonic('C');                                        // Create shortcut
140     createRadioButtonDropDown(colorMenu, colorActions, blueAction);
141     menuBar.add(colorMenu);                                            // Add the color menu
142   }
143 
144   // Menu creation helper
145   private void createRadioButtonDropDown(JMenu menu, Action[] actions, Action selected) {
146     ButtonGroup group = new ButtonGroup();
147     JRadioButtonMenuItem item = null;
148     for(Action action : actions) {
149       group.add(menu.add(item = new JRadioButtonMenuItem(action)));
150       if(action == selected) {
151         item.setSelected(true);                                        // This is default selected
152       }
153     }
154   }
155 
156   // Create toolbar buttons on the toolbar
157   private void createToolbar() {
158     for(FileAction action: fileActions){
159       if(action != exitAction && action != closeAction)
160         addToolbarButton(action);                                      // Add the toolbar button
161     }
162     toolBar.addSeparator();
163 
164     // Create Color menu buttons
165     for(ColorAction action:colorActions){
166         addToolbarButton(action);                                      // Add the toolbar button
167     }
168     toolBar.addSeparator();
169 
170     // Create Elements menu buttons
171     for(TypeAction action:typeActions){
172         addToolbarButton(action);                                      // Add the toolbar button
173     }
174  }
175 
176   // Create and add a toolbar button
177   private void addToolbarButton(Action action) {
178     JButton button = new JButton(action);                              // Create from Action
179     button.setBorder(BorderFactory.createCompoundBorder(               // Add button border
180            new EmptyBorder(2,5,5,2),                                   // Outside border
181            BorderFactory.createRaisedBevelBorder()));                  // Inside border
182     button.setHideActionText(true);                                    // No label on the button
183     toolBar.add(button);                                               // Add the toolbar button
184   }
185 
186   // Set radio button menu checks
187   private void setChecks(JMenu menu, Object eventSource) {
188     if(eventSource instanceof JButton){
189       JButton button = (JButton)eventSource;
190       Action action = button.getAction();
191       for(int i = 0 ; i < menu.getItemCount() ; ++i) {
192         JMenuItem item = menu.getItem(i);
193         item.setSelected(item.getAction() == action);
194       }
195     }
196   }
197 
198   // Inner class defining Action objects for File menu items
199   class FileAction extends AbstractAction {
200     // Create action with a name
201     FileAction(String name) {
202       super(name);
203     }
204 
205     // Create action with a name and accelerator
206     FileAction(String name, char ch, int modifiers) {
207       super(name);
208       putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
209 
210       // Now find the character to underline
211       int index = name.toUpperCase().indexOf(ch);
212       if(index != -1) {
213         putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
214       }
215     }
216 
217     // Event handler
218     public void actionPerformed(ActionEvent e) {
219       // You will add action code here eventually...
220     }
221   }
222 
223   // Inner class defining Action objects for Element type menu items
224   class TypeAction extends AbstractAction {
225     // Create action with just a name property
226     TypeAction(String name, int typeID) {
227       super(name);
228       this.typeID = typeID;
229     }
230 
231     // Create action with a name and an accelerator
232     private TypeAction(String name,int typeID, char ch, int modifiers) {
233       this(name, typeID);
234       putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
235 
236       // Now find the character to underline
237       int index = name.toUpperCase().indexOf(ch);
238       if(index != -1) {
239         putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
240       }
241     }
242 
243     public void actionPerformed(ActionEvent e) {
244       elementType = typeID;
245       setChecks(elementMenu, e.getSource());
246     }
247 
248     private int typeID;
249   }
250 
251   // Handles color menu items
252   class ColorAction  extends AbstractAction {
253     // Create an action with a name and a color
254     public ColorAction(String name, Color color) {
255       super(name);
256       this.color = color;
257     }
258 
259     // Create an action with a name, a color, and an accelerator
260     public ColorAction(String name, Color color, char ch, int modifiers) {
261       this(name, color);
262       putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers));
263 
264       // Now find the character to underline
265       int index = name.toUpperCase().indexOf(ch);
266       if(index != -1) {
267         putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
268       }
269     }
270 
271     public void actionPerformed(ActionEvent e) {
272       elementColor = color;
273       setChecks(colorMenu, e.getSource());
274     }
275 
276     private Color color;
277   }
278 
279   // File actions
280   private FileAction newAction, openAction, closeAction, saveAction, saveAsAction, printAction, exitAction;
281   private FileAction[] fileActions;                                    // File actions as an array
282 
283   // Element type actions
284   private TypeAction lineAction, rectangleAction, circleAction, curveAction;
285   private TypeAction[] typeActions;                                    // Type actions as an array
286 
287 // Element color actions
288   private ColorAction redAction, yellowAction,greenAction, blueAction;
289   private ColorAction[] colorActions;                                  // Color actions as an array
290 
291   private JMenuBar menuBar = new JMenuBar();                           // Window menu bar
292   private JMenu elementMenu;                                           // Elements menu
293   private JMenu colorMenu;                                             // Color menu
294 
295   private Color elementColor = DEFAULT_ELEMENT_COLOR;                  // Current element color
296   private int elementType = DEFAULT_ELEMENT_TYPE;                      // Current element type
297   private JToolBar toolBar = new JToolBar();                           // Window toolbar
298 }
 1 // Sketching application
 2 import javax.swing.*;
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 
 6 public class Sketcher {
 7   public static void main(String[] args) {
 8      theApp = new Sketcher();                                          // Create the application object
 9    SwingUtilities.invokeLater(new Runnable() {
10             public void run() {
11                           theApp.createGUI();                          // Call GUI creator
12             }
13         });
14   }
15 
16   // Method to create the application GUI
17   private void createGUI() {
18     window = new SketcherFrame("Sketcher");                            // Create the app window
19     Toolkit theKit = window.getToolkit();                              // Get the window toolkit
20     Dimension wndSize = theKit.getScreenSize();                        // Get screen size
21 
22     // Set the position to screen center & size to half screen size
23     window.setSize(wndSize.width/2, wndSize.height/2);                 // Set window size
24     window.setLocationRelativeTo(null);                                // Center window
25 
26     window.addWindowListener(new WindowHandler());                     // Add window listener
27     window.setVisible(true);
28   }
29 
30   // Handler class for window events
31   class WindowHandler extends WindowAdapter {
32     // Handler for window closing event
33     @Override
34     public void windowClosing(WindowEvent e) {
35       // Code to be added here...
36     }
37   }
38 
39   private SketcherFrame window;                                        // The application window
40   private static Sketcher theApp;                                      // The application object
41 }
原文地址:https://www.cnblogs.com/mannixiang/p/3486717.html