Java基础之扩展GUI——添加状态栏(Sketcher 1 with a status bar)
控制台程序。
为了显示各个应用程序参数的状态,并且将各个参数显示在各自的面板中,在应用程序窗口的底部添加状态栏是常见且非常方便的方式。
定义状态栏时没有Swing类可用,所以必须自己建立StatusBar类。在理想情况下,应为一般目地的状态栏设计类,然后再针对Sketcher进行定制。但由于篇幅显示,这里采用简单方法说明如何设计专用语Sketcher的类。
// Class defining a status bar
import javax.swing.*;
import java.awt.*;
import javax.swing.border.BevelBorder;
import static Constants.SketcherConstants.*; @SuppressWarnings("serial")
class StatusBar extends JPanel {
// Constructor
public StatusBar() {
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 3));
setBackground(Color.LIGHT_GRAY);
setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
setColorPane(DEFAULT_ELEMENT_COLOR);
setTypePane(DEFAULT_ELEMENT_TYPE);
add(colorPane); // Add color pane to status bar
add(typePane); // Add type pane to status bar
} // Set color pane contents
public void setColorPane(Color color) {
String text = null; // Text for the color pane
Icon icon = null; // Icon to be displayed
if(color.equals(Color.RED)) {
text = "RED";
icon = RED16;
} else if(color.equals(Color.YELLOW)) {
text = "YELLOW";
icon = YELLOW16;
} else if(color.equals(Color.GREEN)) {
text = "GREEN";
icon = GREEN16;
} else if(color.equals(Color.BLUE)) {
text = "BLUE";
icon = BLUE16;
} else {
text = "CUSTOM COLOR";
}
colorPane.setIcon(icon);
colorPane.setText(text); // Set the pane text
} // Set type pane label
public void setTypePane (int elementType) {
String text = null; // Text for the type pane
switch(elementType) {
case LINE:
text = "LINE";
break;
case RECTANGLE:
text = "RECTANGLE";
break;
case CIRCLE:
text = "CIRCLE";
break;
case CURVE:
text = "CURVE";
break;
default:
assert false;
}
typePane.setText(text); // Set the pane text
} // Panes in the status bar
private StatusPane colorPane = new StatusPane("BLUE", BLUE16);;
private StatusPane typePane = new StatusPane("LINE"); // Class defining a status bar pane
class StatusPane extends JLabel {
// Constructor - text only
public StatusPane(String text) {
super(text, LEFT);
setupPane();
} // Constructor - text with an icon
public StatusPane(String text, Icon icon) {
super(text, icon, LEFT);
setupPane();
} // Helper method for use by constructors
private void setupPane() {
setBackground(Color.LIGHT_GRAY); // Set background color
setForeground(Color.BLACK); // Set foreground color
setFont(paneFont); // Set the fixed font
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED), // Outside border
BorderFactory.createEmptyBorder(0,5,0,3))); // Inside border
setPreferredSize(new Dimension(80,20));
} // Font for pane text
private Font paneFont = new Font("Serif", Font.PLAIN, 10);
}
}
然后,在SketcherFrame类中添加对状态栏的定义:
// Frame for the Sketcher application
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*; import static java.awt.event.InputEvent.*;
import static java.awt.Color.*;
import static Constants.SketcherConstants.*;
import static javax.swing.Action.*; @SuppressWarnings("serial")
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title, Sketcher theApp) {
setTitle(title); // Set the window title
this.theApp = theApp; // Save app. object reference
setJMenuBar(menuBar); // Add the menu bar to the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // Default is exit the application createFileMenu(); // Create the File menu
createElementMenu(); // Create the element menu
createColorMenu(); // Create the element menu
createToolbar();
toolBar.setRollover(true);
getContentPane().add(toolBar, BorderLayout.NORTH); // Add the toolbar
getContentPane().add(statusBar, BorderLayout.SOUTH); // Add the statusbar
} // Create File menu item actions
private void createFileMenuActions() {
newAction = new FileAction("New", 'N', CTRL_DOWN_MASK);
openAction = new FileAction("Open", 'O', CTRL_DOWN_MASK);
closeAction = new FileAction("Close");
saveAction = new FileAction("Save", 'S', CTRL_DOWN_MASK);
saveAsAction = new FileAction("Save As...");
printAction = new FileAction("Print", 'P', CTRL_DOWN_MASK);
exitAction = new FileAction("Exit", 'X', CTRL_DOWN_MASK); // Initialize the array
FileAction[] actions = {openAction, closeAction, saveAction, saveAsAction, printAction, exitAction};
fileActions = actions; // Add toolbar icons
newAction.putValue(LARGE_ICON_KEY, NEW24);
openAction.putValue(LARGE_ICON_KEY, OPEN24);
saveAction.putValue(LARGE_ICON_KEY, SAVE24);
saveAsAction.putValue(LARGE_ICON_KEY, SAVEAS24);
printAction.putValue(LARGE_ICON_KEY, PRINT24); // Add menu item icons
newAction.putValue(SMALL_ICON, NEW16);
openAction.putValue(SMALL_ICON, OPEN16);
saveAction.putValue(SMALL_ICON, SAVE16);
saveAsAction.putValue(SMALL_ICON,SAVEAS16);
printAction.putValue(SMALL_ICON, PRINT16); // Add tooltip text
newAction.putValue(SHORT_DESCRIPTION, "Create a new sketch");
openAction.putValue(SHORT_DESCRIPTION, "Read a sketch from a file");
closeAction.putValue(SHORT_DESCRIPTION, "Close the current sketch");
saveAction.putValue(SHORT_DESCRIPTION, "Save the current sketch to file");
saveAsAction.putValue(SHORT_DESCRIPTION, "Save the current sketch to a new file");
printAction.putValue(SHORT_DESCRIPTION, "Print the current sketch");
exitAction.putValue(SHORT_DESCRIPTION, "Exit Sketcher");
} // Create the File menu
private void createFileMenu() {
JMenu fileMenu = new JMenu("File"); // Create File menu
fileMenu.setMnemonic('F'); // Create shortcut
createFileMenuActions(); // Create Actions for File menu item // Construct the file drop-down menu
fileMenu.add(newAction); // New Sketch menu item
fileMenu.add(openAction); // Open sketch menu item
fileMenu.add(closeAction); // Close sketch menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(saveAction); // Save sketch to file
fileMenu.add(saveAsAction); // Save As menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(printAction); // Print sketch menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(exitAction); // Print sketch menu item
menuBar.add(fileMenu); // Add the file menu
} // Create Element menu actions
private void createElementTypeActions() {
lineAction = new TypeAction("Line", LINE, 'L', CTRL_DOWN_MASK);
rectangleAction = new TypeAction("Rectangle", RECTANGLE, 'R', CTRL_DOWN_MASK);
circleAction = new TypeAction("Circle", CIRCLE,'C', CTRL_DOWN_MASK);
curveAction = new TypeAction("Curve", CURVE,'U', CTRL_DOWN_MASK); // Initialize the array
TypeAction[] actions = {lineAction, rectangleAction, circleAction, curveAction};
typeActions = actions; // Add toolbar icons
lineAction.putValue(LARGE_ICON_KEY, LINE24);
rectangleAction.putValue(LARGE_ICON_KEY, RECTANGLE24);
circleAction.putValue(LARGE_ICON_KEY, CIRCLE24);
curveAction.putValue(LARGE_ICON_KEY, CURVE24); // Add menu item icons
lineAction.putValue(SMALL_ICON, LINE16);
rectangleAction.putValue(SMALL_ICON, RECTANGLE16);
circleAction.putValue(SMALL_ICON, CIRCLE16);
curveAction.putValue(SMALL_ICON, CURVE16); // Add tooltip text
lineAction.putValue(SHORT_DESCRIPTION, "Draw lines");
rectangleAction.putValue(SHORT_DESCRIPTION, "Draw rectangles");
circleAction.putValue(SHORT_DESCRIPTION, "Draw circles");
curveAction.putValue(SHORT_DESCRIPTION, "Draw curves");
} // Create the Elements menu
private void createElementMenu() {
createElementTypeActions();
elementMenu = new JMenu("Elements"); // Create Elements menu
elementMenu.setMnemonic('E'); // Create shortcut
createRadioButtonDropDown(elementMenu, typeActions, lineAction);
menuBar.add(elementMenu); // Add the element menu
} // Create Color menu actions
private void createElementColorActions() {
redAction = new ColorAction("Red", RED, 'R', CTRL_DOWN_MASK|ALT_DOWN_MASK);
yellowAction = new ColorAction("Yellow", YELLOW, 'Y', CTRL_DOWN_MASK|ALT_DOWN_MASK);
greenAction = new ColorAction("Green", GREEN, 'G', CTRL_DOWN_MASK|ALT_DOWN_MASK);
blueAction = new ColorAction("Blue", BLUE, 'B', CTRL_DOWN_MASK|ALT_DOWN_MASK); // Initialize the array
ColorAction[] actions = {redAction, greenAction, blueAction, yellowAction};
colorActions = actions; // Add toolbar icons
redAction.putValue(LARGE_ICON_KEY, RED24);
greenAction.putValue(LARGE_ICON_KEY, GREEN24);
blueAction.putValue(LARGE_ICON_KEY, BLUE24);
yellowAction.putValue(LARGE_ICON_KEY, YELLOW24); // Add menu item icons
redAction.putValue(SMALL_ICON, RED16);
greenAction.putValue(SMALL_ICON, GREEN16);
blueAction.putValue(SMALL_ICON, BLUE16);
yellowAction.putValue(SMALL_ICON, YELLOW16); // Add tooltip text
redAction.putValue(SHORT_DESCRIPTION, "Draw in red");
greenAction.putValue(SHORT_DESCRIPTION, "Draw in green");
blueAction.putValue(SHORT_DESCRIPTION, "Draw in blue");
yellowAction.putValue(SHORT_DESCRIPTION, "Draw in yellow");
} // Create the Color menu
private void createColorMenu() {
createElementColorActions();
colorMenu = new JMenu("Color"); // Create Elements menu
colorMenu.setMnemonic('C'); // Create shortcut
createRadioButtonDropDown(colorMenu, colorActions, blueAction);
menuBar.add(colorMenu); // Add the color menu
} // Menu creation helper
private void createRadioButtonDropDown(JMenu menu, Action[] actions, Action selected) {
ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem item = null;
for(Action action : actions) {
group.add(menu.add(item = new JRadioButtonMenuItem(action)));
if(action == selected) {
item.setSelected(true); // This is default selected
}
}
} // Create toolbar buttons on the toolbar
private void createToolbar() {
for(FileAction action: fileActions){
if(action != exitAction && action != closeAction)
addToolbarButton(action); // Add the toolbar button
}
toolBar.addSeparator(); // Create Color menu buttons
for(ColorAction action:colorActions){
addToolbarButton(action); // Add the toolbar button
} toolBar.addSeparator(); // Create Elements menu buttons
for(TypeAction action:typeActions){
addToolbarButton(action); // Add the toolbar button
}
} // Create and add a toolbar button
private void addToolbarButton(Action action) {
JButton button = new JButton(action); // Create from Action
button.setBorder(BorderFactory.createCompoundBorder( // Add button border
new EmptyBorder(2,5,5,2), // Outside border
BorderFactory.createRaisedBevelBorder())); // Inside border
button.setHideActionText(true); // No label on the button
toolBar.add(button); // Add the toolbar button
} // Return the current drawing color
public Color getElementColor() {
return elementColor;
} // Return the current element type
public int getElementType() {
return elementType;
} // Set radio button menu checks
private void setChecks(JMenu menu, Object eventSource) {
if(eventSource instanceof JButton){
JButton button = (JButton)eventSource;
Action action = button.getAction();
for(int i = 0 ; i<menu.getItemCount() ; ++i) {
JMenuItem item = menu.getItem(i);
item.setSelected(item.getAction() == action);
}
}
} // Inner class defining Action objects for File menu items
class FileAction extends AbstractAction {
// Create action with a name
FileAction(String name) {
super(name);
} // Create action with a name and accelerator
FileAction(String name, char ch, int modifiers) {
super(name);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} // Event handler
public void actionPerformed(ActionEvent e) {
// You will add action code here eventually...
}
} // Inner class defining Action objects for Element type menu items
class TypeAction extends AbstractAction {
// Create action with just a name property
TypeAction(String name, int typeID) {
super(name);
this.typeID = typeID;
} // Create action with a name and an accelerator
private TypeAction(String name,int typeID, char ch, int modifiers) {
this(name, typeID);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} public void actionPerformed(ActionEvent e) {
elementType = typeID;
setChecks(elementMenu, e.getSource());
statusBar.setTypePane(typeID);
} private int typeID;
} // Handles color menu items
class ColorAction extends AbstractAction {
// Create an action with a name and a color
public ColorAction(String name, Color color) {
super(name);
this.color = color;
} // Create an action with a name, a color, and an accelerator
public ColorAction(String name, Color color, char ch, int modifiers) {
this(name, color);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} public void actionPerformed(ActionEvent e) {
elementColor = color;
setChecks(colorMenu, e.getSource());
statusBar.setColorPane(color);
} private Color color;
} // File actions
private FileAction newAction, openAction, closeAction, saveAction, saveAsAction, printAction, exitAction;
private FileAction[] fileActions; // File actions as an array // Element type actions
private TypeAction lineAction, rectangleAction, circleAction, curveAction;
private TypeAction[] typeActions; // Type actions as an array // Element color actions
private ColorAction redAction, yellowAction,greenAction, blueAction;
private ColorAction[] colorActions; // Color actions as an array private JMenuBar menuBar = new JMenuBar(); // Window menu bar
private JMenu elementMenu; // Elements menu
private JMenu colorMenu; // Color menu
private StatusBar statusBar = new StatusBar(); // Window status bar private Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
private JToolBar toolBar = new JToolBar(); // Window toolbar
private Sketcher theApp; // The application object
}
其他与上一例同。
Java基础之扩展GUI——添加状态栏(Sketcher 1 with a status bar)的更多相关文章
- Java基础之扩展GUI——高亮元素、上下文菜单、移动旋转元素、自定义颜色(Sketcher 10)
窗口应用程序. 本例在上一版的基础上实现了高亮元素.移动元素.上下文菜单.旋转元素.设置自定义颜色. 1.自定义常量包: // Defines application wide constants p ...
- Java基础之扩展GUI——使用字体对话框(Sketcher 5 displaying a font dialog)
控制台程序. 为了可以选择系统支持的字体,我们定义了一个FontDialog类: // Class to define a dialog to choose a font import java.aw ...
- Java基础之扩展GUI——使用对话框创建文本元素(Sketcher 4 creating text elements)
控制台程序. 为了与Sketcher中的其他元素类型保持一致,需要为Elements菜单添加Text菜单项和工具栏按钮.还需要定义用来表示文本元素的类Element.Text. 1.修改Sketche ...
- Java基础之扩展GUI——显示About对话框(Sketcher 2 displaying an About dialog)
控制台程序. 最简单的对话框仅仅显示一些信息.为了说明这一点,可以为Sketcher添加Help菜单项和About菜单项,之后再显示About对话框来提供有关应用程序的信息. 要新建的对话框类从JDi ...
- 【Java基础总结】GUI
GUI(Graphical User Interface),图形用户接口 CLI(Command Line User Interface),命令行用户接口 1. 容器 Container GUI主要位 ...
- Java基础--Java---IO流------GUI(布局)、Frame、事件监听机制、窗体事件、Action事件、鼠标事件、对话框Dialog、键盘事件、菜单
* 创建图形化界面 * 1.创建frame窗体 * 2.对窗体进行基本设置 * 比如大小.位置.布局 * 3.定义组件 * 4.将组件通过窗体的add方法添加到窗体 * 5.让窗体显 ...
- java基础学习总结——GUI编程(二)
一.事件监听
- java基础学习总结——GUI编程(一)
一.AWT介绍
- java基础学习总结——GUI编程(二) 未学习
一.事件监听
随机推荐
- Codeforces Beta Round #3
A题,水题,还是无法1Y. B题,题意是类似背包的问题,在v的容量下,有1重量和2重量的,如果达到价值最大. 贪心,写的很恶心.看着数据过了. 奇数的时候,先选一个1.之后然后1+1 和 2 比较就行 ...
- HDU 4722 Good Numbers(DP)
题目链接 脑子有点乱,有的地方写错了,尚大婶鄙视了... 来个模版的. #include <iostream> #include <cstdio> #include <c ...
- java画图程序_图片用字母画出来
最近在研究怎样将图片用字母在文本编辑工具中“画”出来. 你看了这个可能还不知道我想说什么? 我想直接上图,大家一定就知道了 第一张:小猫 原图:http://www.cnblogs.com/hongt ...
- Solr JAVA客户端SolrJ 4.9使用示例教程
http://my.oschina.net/cloudcoder/blog/305024 简介 SolrJ是操作Solr的JAVA客户端,它提供了增加.修改.删除.查询Solr索引的JAVA接口.So ...
- C#常用方法二
public sealed class StringTool { /// <summary> /// 将txt文件读入字符串 /// </summary> /// <pa ...
- mongodb数据导入导出以及备份恢复
昨日在公司收到游戏方发来一个1G多的数据文件,要求导入联运账号中.细细一看,纳尼!文件竟然是BSON格式. 哇塞,这不是去年给大家分享的NoSql中的MongoDB的备份文件吗? 于是搭好环境 1.启 ...
- MongoDB数据库的简介及安装
一.MongoDB数据库简介 简介 MongoDB是一个高性能,开源,无模式的,基于分布式文件存储的文档型数据库,由C++语言编写,其名称来源取自“humongous”,是一种开源的文档数据库──No ...
- java基础--java静态代码块和静态方法的区别、static用法
转载自: http://blog.sina.com.cn/s/blog_afddb8ff0101aqs9.html 静态代码块:有些代码必须在项目启动的时候就执行,这种代码是主动执行的(当类被载入时, ...
- 改centos7的网卡名
学习参考的文章,地址双手奉上http://www.linuxidc.com/Linux/2015-09/123396.htm 1.查看服务器的流量使用情况,执行命令cat /proc/net/dev ...
- Mysql的实时同步 - 双机互备
设置方法: 步一设 A 服务服 (192.168.1.43) 上用户为 backup, 123456 , 同步的数据库为test; B 服务服 (192.168.1.23) 上用户为 root, 12 ...