Java基础之处理事件——添加工具提示(Sketcher 9 with tooltips)

控制台程序。

在Java中实现对工具提示的支持是非常简单的,秘诀仍在我们一直使用的Action对象中。Action对象拥有存储工具提示文本的内置功能因为文本是通过SHORT_DESCRIPTION键提供的,我们只需要把工具提示文本存储为这个键的值即可。

下面仅列出修改后的SketcherFrame类:

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