控制台程序。

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

定义状态栏时没有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 ; i<menu.getItemCount() ; ++i) {
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)相关推荐

  1. Java基础之扩展GUI——高亮元素、上下文菜单、移动旋转元素、自定义颜色(Sketcher 10)...

    窗口应用程序. 本例在上一版的基础上实现了高亮元素.移动元素.上下文菜单.旋转元素.设置自定义颜色. 1.自定义常量包: 1 // Defines application wide constants ...

  2. Java基础之扩展GUI——使用字体对话框(Sketcher 5 displaying a font dialog)

    控制台程序. 为了可以选择系统支持的字体,我们定义了一个FontDialog类: 1 // Class to define a dialog to choose a font 2 import jav ...

  3. Java基础之扩展GUI——显示About对话框(Sketcher 2 displaying an About dialog)

    控制台程序. 最简单的对话框仅仅显示一些信息.为了说明这一点,可以为Sketcher添加Help菜单项和About菜单项,之后再显示About对话框来提供有关应用程序的信息. 要新建的对话框类从JDi ...

  4. Java基础之扩展特性

    Java基础之扩展特性 一.泛型 二.包装类 三.递归算法 四.异常处理 五.自定义异常 六.常用类 七.String 的正则表达式 八.Java 和 C++的区别 九.TCP/IP 初识 十.Soc ...

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

    控制台程序. 要为菜单项添加图标以补充工具栏图标,只需要在创建菜单项的Action对象中添加IconImage对象,作为SMALL_ICON键的值即可. 1 // Defines applicatio ...

  6. Java基础之处理事件——实现低级事件监听器(Sketcher 2 implementing a low-level listener)...

    控制台程序. 定义事件监听器的类必须实现监听器接口.所有的事件监听器接口都扩展了java.util.EventListener接口.这个接口没有声明任何方法,仅仅用于表示监听器对象.使用EventLi ...

  7. Java基础之在窗口中绘图——使用模型/视图体系结构在视图中绘图(Sketcher 1 drawing a 3D rectangle)...

    控制台程序. 在模型中表示数据视图的类用来显示草图并处理用户的交互操作,所以这种类把显示方法和草图控制器合并在一起.不专用于某个视图的通用GUI创建和操作在SketcherFrame类中处理. 模型对 ...

  8. Java基础之处理事件——使用适配器类(Sketcher 3 using an Adapter class)

    控制台程序. 适配器类是指实现了监听器接口的类,但监听器接口中的方法没有内容,所以它们什么也不做.背后的思想是:允许从提供的适配器类派生自己的监听器类,之后再实现那些自己感兴趣的类.其他的空方法会从适 ...

  9. Java基础之在窗口中绘图——利用多态性使用鼠标自由绘图(Sketcher 7 with a crosshair cursor)...

    控制台程序. 在Sketcher中创建形状时,并不知道应该以什么顺序创建不同类型的形状,这完全取决于使用Sketcher程序生成草图的人.因此需要绘制形状,对它们执行其他操作而不必知道图形是什么.当然 ...

最新文章

  1. 如何用matlab求方程的整数解
  2. 使用SAP Spartacus快速创建一个电商店铺网站
  3. php array_merge 与 + 区别
  4. springboot动态数据源切换(多数据源配置)
  5. tomcat ---- 常用服务器
  6. VB获取系统目录的简单方法
  7. android接支付宝授权和支付功能
  8. caffe 安装(only cpu)
  9. win7定时关机命令是什么
  10. SQL Server学习笔记3: SQL Server2005集群上的SP3补丁升级步骤
  11. avr单片机c语言程序设计,avr单片机c语言编程风格介绍
  12. 一名IT民工开通博客
  13. Linux 好书、经典书籍推荐
  14. C++中std::setw()的用法
  15. 暑假训练---三棱锥内切球公式及海伦公式
  16. (转)微信公众号发表情 Emoji
  17. The Relationship Cure
  18. 解决问题https访问http加载不出图片资源的顺便在给逻辑做个马杀鸡
  19. 科技新品 | 大疆航拍小飞机重量不到249克;绘王数位屏薄至12毫米;追觅科技机器人吸尘器低至65分贝静音水平...
  20. linux sendmail 总结

热门文章

  1. html5的网页布局工具,HTML5网站响应式布局的主流设计方法介绍及工具推荐
  2. 基于 ASK + EB 构建容器事件驱动服务
  3. 阿里巴巴云原生应用安全防护实践与 OpenKruise 的新领域
  4. 心灵战争服务器维护,心灵战争服务器异常产生哪些问题如何解决_心灵战争服务器异常产生问题及解决方法_玩游戏网...
  5. 前端iframe 能指定本地网页吗_微前端的技术拆分方式
  6. 类路径是什么意思_多播是什么意思 多播介绍【详解】
  7. python:实现简单的web开发demo
  8. AttributeError: 'NoneType' object has no attribute 'grid'报错解决方案
  9. 基于直方图的图像增强算法(HE、CLAHE、Retinex)
  10. 【视频课】图像分割重磅上新-人像抠图(Matting)实战