Java基础之扩展GUI——添加状态栏(Sketcher 1 with a status bar)

控制台程序。

为了显示各个应用程序参数的状态,并且将各个参数显示在各自的面板中,在应用程序窗口的底部添加状态栏是常见且非常方便的方式。

定义状态栏时没有Swing类可用,所以必须自己建立StatusBar类。在理想情况下,应为一般目地的状态栏设计类,然后再针对Sketcher进行定制。但由于篇幅显示,这里采用简单方法说明如何设计专用语Sketcher的类。

 1 // Class defining a status bar
 2 import javax.swing.*;
 3 import java.awt.*;
 4 import javax.swing.border.BevelBorder;
 5 import static Constants.SketcherConstants.*;
 6 
 7 @SuppressWarnings("serial")
 8 class StatusBar extends JPanel {
 9   // Constructor
10   public StatusBar() {
11     setLayout(new FlowLayout(FlowLayout.LEFT, 10, 3));
12     setBackground(Color.LIGHT_GRAY);
13     setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
14     setColorPane(DEFAULT_ELEMENT_COLOR);
15     setTypePane(DEFAULT_ELEMENT_TYPE);
16     add(colorPane);                                                    // Add color pane to status bar
17     add(typePane);                                                     // Add type pane to status bar
18   }
19 
20   // Set color pane contents
21   public void setColorPane(Color color) {
22     String text = null;                                                // Text for the color pane
23     Icon icon = null;                                                  // Icon to be displayed
24     if(color.equals(Color.RED)) {
25       text = "RED";
26       icon = RED16;
27     } else if(color.equals(Color.YELLOW)) {
28       text = "YELLOW";
29       icon = YELLOW16;
30     } else if(color.equals(Color.GREEN)) {
31       text = "GREEN";
32       icon = GREEN16;
33     } else if(color.equals(Color.BLUE)) {
34       text = "BLUE";
35       icon = BLUE16;
36     } else {
37       text = "CUSTOM COLOR";
38     }
39     colorPane.setIcon(icon);
40     colorPane.setText(text);                                           // Set the pane text
41   }
42 
43   // Set type pane label
44   public void setTypePane (int elementType) {
45     String text = null;                                                // Text for the type pane
46     switch(elementType) {
47       case LINE:
48         text = "LINE";
49         break;
50       case RECTANGLE:
51         text = "RECTANGLE";
52         break;
53       case CIRCLE:
54         text = "CIRCLE";
55         break;
56       case CURVE:
57         text = "CURVE";
58         break;
59       default:
60         assert false;
61     }
62     typePane.setText(text);                                            // Set the pane text
63   }
64 
65   // Panes in the status bar
66   private StatusPane colorPane = new StatusPane("BLUE", BLUE16);;
67   private StatusPane typePane = new StatusPane("LINE");
68 
69   // Class defining a status bar pane
70   class StatusPane extends JLabel {
71     // Constructor - text only
72     public StatusPane(String text) {
73       super(text, LEFT);
74       setupPane();
75     }
76 
77     // Constructor - text with an icon
78     public StatusPane(String text, Icon icon) {
79       super(text, icon, LEFT);
80       setupPane();
81     }
82 
83     // Helper method for use by constructors
84     private void setupPane() {
85       setBackground(Color.LIGHT_GRAY);                                 // Set background color
86       setForeground(Color.BLACK);                                      // Set foreground color
87       setFont(paneFont);                                               // Set the fixed font
88       setBorder(BorderFactory.createCompoundBorder(
89         BorderFactory.createBevelBorder(BevelBorder.LOWERED),          // Outside border
90         BorderFactory.createEmptyBorder(0,5,0,3)));                    // Inside border
91       setPreferredSize(new Dimension(80,20));
92     }
93 
94     // Font for pane text
95     private Font paneFont = new Font("Serif", Font.PLAIN, 10);
96   }
97 }

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

其他与上一例同。

转载于:https://www.cnblogs.com/mannixiang/p/3494935.html

你可能感兴趣的:(Java基础之扩展GUI——添加状态栏(Sketcher 1 with a status bar))