Java基础之处理事件——添加工具栏(Sketcher 7 with File toolbar buttons)
控制台程序。
工具栏在应用程序窗口中通常位于内容面板顶部的菜单栏下,包含直接访问菜单选项的按钮。在Sketcher程序中可以为最常用的菜单项添加工具栏。
工具栏是javax.swing.JToolBar类定义的Swing组件。想SketcherFrame类定义中添加如下域,可以为这个类添加一个用于工具栏的成员:
private JToolBar toolBar = new JToolBar();
为了把工具栏添加到应用程序窗口中,需要在SkecherFrame构造函数已有代码的后面添加如下语句:
getContentPane().add(toolBar,BorderLayout.NORTH);
对图标的引用一般存储在javax.swing.Icon类型的变量中,javax.swing.Icon是接口,其中声明的方法getHeight()和getWidth()分别用来返回图标的高度和宽度(以像素为单位)。Icon接口还声明了paint()方法,用来在组件上绘制图标图像。javax.swing.ImageIcon类实现了Icon接口,使用这个类在程序中通过包含定义图标图像数据的文件来创建图标对象。
ImageIcon类有多个构造函数,这里使用的构造函数仅仅接收一个String参数,这个参数指定了包含图标图像的文件的路径。传送为参数的String对象可以只是文件名,此时文件应位于Sketcher执行时的当前目录下。
在自定义包中指定图标文件的路径:
// Defines application wide constants
package Constants;
import java.awt.Color;
import javax.swing.*; public class SketcherConstants {
// Path for images
public final static String imagePath = "E:/JavaProject/BeginningJava/Images/"; // Toolbar icons
public final static Icon NEW24 = new ImageIcon(imagePath + "New24.gif");
public final static Icon OPEN24 = new ImageIcon(imagePath + "Open24.gif");
public final static Icon SAVE24 = new ImageIcon(imagePath + "Save24.gif");
public final static Icon SAVEAS24 = new ImageIcon(imagePath + "SaveAs24.gif");
public final static Icon PRINT24 = new ImageIcon(imagePath + "Print24.gif"); // Element type definitions
public final static int LINE = 101;
public final static int RECTANGLE = 102;
public final static int CIRCLE = 103;
public final static int CURVE = 104; // Initial conditions
public final static int DEFAULT_ELEMENT_TYPE = LINE;
public final static Color DEFAULT_ELEMENT_COLOR = Color.BLUE;
}
// 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.AWTEvent.*;
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) {
setTitle(title); // Set the window title
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);
} // 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);
} // 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;
} // Create the Elements menu
private void createElementMenu() {
createElementTypeActions();
JMenu 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;
} // Create the Color menu
private void createColorMenu() {
createElementColorActions();
JMenu 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
}
} // 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
} // 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;
} 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;
} 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 Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
private JToolBar toolBar = new JToolBar(); // Window toolbar
}
// Sketching application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the application object
SwingUtilities.invokeLater(new Runnable() {
public void run() {
theApp.createGUI(); // Call GUI creator
}
});
} // Method to create the application GUI
private void createGUI() {
window = new SketcherFrame("Sketcher"); // Create the app window
Toolkit theKit = window.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size // Set the position to screen center & size to half screen size
window.setSize(wndSize.width/2, wndSize.height/2); // Set window size
window.setLocationRelativeTo(null); // Center window window.addWindowListener(new WindowHandler()); // Add window listener
window.setVisible(true);
} // Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
@Override
public void windowClosing(WindowEvent e) {
// Code to be added here...
}
} private SketcherFrame window; // The application window
private static Sketcher theApp; // The application object
}
Java基础之处理事件——添加工具栏(Sketcher 7 with File toolbar buttons)的更多相关文章
- Java基础之处理事件——添加菜单图标(Sketcher 8 with toolbar buttons and menu icons)
控制台程序. 要为菜单项添加图标以补充工具栏图标,只需要在创建菜单项的Action对象中添加IconImage对象,作为SMALL_ICON键的值即可. // Defines application ...
- Java基础之处理事件——添加工具提示(Sketcher 9 with tooltips)
控制台程序. 在Java中实现对工具提示的支持是非常简单的,秘诀仍在我们一直使用的Action对象中.Action对象拥有存储工具提示文本的内置功能因为文本是通过SHORT_DESCRIPTION键提 ...
- build path libraries java基础--Jar包添加到build path方式说明--01
摘自: http://blog.csdn.net/haolongabc/article/details/7007701 java基础--Jar包添加到build path方式说明--01 前言:这段短 ...
- Java 基础(三)| IO流之使用 File 类的正确姿势
为跳槽面试做准备,今天开始进入 Java 基础的复习.希望基础不好的同学看完这篇文章,能掌握泛型,而基础好的同学权当复习,希望看完这篇文章能够起一点你的青涩记忆. 一.什么是 File 类? java ...
- Java基础之处理事件——使用动作Action(Sketcher 6 using Action objects)
控制台程序. 动作Action是任何实现了javax.swing.Action接口的类的对象.这个接口声明了操作Action对象的方法,例如,存储与动作相关的属性.启用和禁用动作.Action接口扩展 ...
- Java基础之处理事件——实现低级事件监听器(Sketcher 2 implementing a low-level listener)
控制台程序. 定义事件监听器的类必须实现监听器接口.所有的事件监听器接口都扩展了java.util.EventListener接口.这个接口没有声明任何方法,仅仅用于表示监听器对象.使用EventLi ...
- Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)
控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...
- Java基础之处理事件——使用适配器类(Sketcher 3 using an Adapter class)
控制台程序. 适配器类是指实现了监听器接口的类,但监听器接口中的方法没有内容,所以它们什么也不做.背后的思想是:允许从提供的适配器类派生自己的监听器类,之后再实现那些自己感兴趣的类.其他的空方法会从适 ...
- Java基础之处理事件——使窗口处理自己的事件(Skethcer 1 handing its own closing event)
控制台程序. 为表示事件的常量使用标识符可以直接启用组件对象的特定事件组.调用组件的enableEvent()方法,并把想要启用事件的标识符传送为参数,但这只在不使用监视器的情况下有效.注册监听器会自 ...
随机推荐
- number_format函数的使用
<!-- ###:表示传入的价格,2:保留两位小数,'.':用点区分, --> <!-- 该函数只支持1.2.4个参数.不能只写3个参数 --> <span>< ...
- Bootstrap页面布局3 - BS布局以及流动布局
1. <h1 class='page-header'>布局<small> 使用bootstrap网格系统布局网页</small></h1> 得到如图所示 ...
- Ext TabPanel items高度宽度自适应
写Ext的时候经常会遇到一些莫名其妙,令人感到非常神奇的问题,甚至都没办法用语言去描述它,搞的人想请教一下百度或Google都不知道该去怎么问,简直能够令人发疯.先来看张截图吧. 有没有注意到里面的G ...
- Bluetooth SDP介绍
目录 1. 概念 2. 服务记录(Service Record) 3. 服务属性(Service Attribute) 4. 服务类(Service Class) 5. 服务查找 5.1 UUID 5 ...
- Bluetooth HFP介绍
目录 1. 介绍 1.1 目的 1.2 使用场景 1.3 依赖关系 1.4 协议栈 1.5 角色 2. 应用层 3. 空白章节 4. 互操作性要求 4.1 介绍 4.2 Service Level C ...
- python对象数据的读写权限
面向对象的编程语言在写大型程序的的时候,往往比面向过程的语言用起来更方便,安全.其中原因之一在于:类机制. 类,对众多的数据进行分类,封装,让一个数据对象成为一个完整的个体,贴近现实生活,高度抽象化. ...
- node.js创建服务器报错
创建nodeTest.js如下: var http = require('http'); http.createServer(function (request, response){ respons ...
- JS删除数组条目中重复的条目
[腾讯2015春招web前端开发练习卷] 请给Array本地对象增加一个原型方法,它用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除的重复条目的新数组. Array.prototyp ...
- Arcgis for JS之Cluster聚类分析的实现
原文:Arcgis for JS之Cluster聚类分析的实现 在做项目的时候,碰见了这样一个问题:给地图上标注点对象,数据是从数据库来 的,包含XY坐标信息的,通过graphic和graphicla ...
- self.nsme 和 _name 的问题
.h文件 @interface myclass:NSObject @property(nonatomic,retain)NSArray*MyArray; @end .m文件 @implementati ...