控制台程序。

动作Action是任何实现了javax.swing.Action接口的类的对象。这个接口声明了操作Action对象的方法,例如,存储与动作相关的属性、启用和禁用动作。Action接口扩展了ActionListener接口,所以Action对象既是监听器,也是动作。

一些Swing组件,包括JMenu和JToolBar类型的组件,都有add()方法,可以接受Action类型的参数。当使用add()方法把Action对象添加到JMenu对象中,add()方法就会创建类型自动正确的组件。如果把Action对象添加到JMenu对象中,add()方法就会创建并返回JmentItem对象。另一方面,当把相同的Action对象添加到Action对象中时,会创建并返回JButton类型的对象。这意味着可以给菜单和工具栏添加相同的Action对象,因为Action对象是自己的监听器,所以可以自动获得由相同动作支持的菜单项和工具栏按钮。

下面使用Action重建SketcherFrame类:

 // Frame for the Sketcher application
import javax.swing.*;
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.*; @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
} // 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;
} // 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 Element 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 Element 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();
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
}
}
} // 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; // This is temporary just to show it works...
getContentPane().setBackground(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 Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
}

需要3个内部类来定义动作:一个用于File菜单项;第二个用于元素类型菜单项;第三个用于元素颜色菜单项。这些类都派生于实现了Aciton接口的javax.swing.AbstractAction类。AbstractAction类有3个构造函数,无参构造函数会创建带有默认名称和图标的对象;可以仅仅提供String类型的名称参数,此时会获得默认图标;最后,还可以提供名称和Icon类型的图标作为参数。
其它部分和以前一样:

 // 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 {
@Override
// Handler for window closing event
public void windowClosing(WindowEvent e) {
// Code to be added here...
}
} private SketcherFrame window; // The application window
private static Sketcher theApp; // The application object
}

导入自定义包文件:

 // Defines application wide constants
package Constants;
import java.awt.Color; public class SketcherConstants {
// 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;
}

Java基础之处理事件——使用动作Action(Sketcher 6 using Action objects)的更多相关文章

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

    控制台程序. 在Java中实现对工具提示的支持是非常简单的,秘诀仍在我们一直使用的Action对象中.Action对象拥有存储工具提示文本的内置功能因为文本是通过SHORT_DESCRIPTION键提 ...

  2. Java基础之处理事件——添加工具栏(Sketcher 7 with File toolbar buttons)

    控制台程序. 工具栏在应用程序窗口中通常位于内容面板顶部的菜单栏下,包含直接访问菜单选项的按钮.在Sketcher程序中可以为最常用的菜单项添加工具栏. 工具栏是javax.swing.JToolBa ...

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

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

  4. Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)

    控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...

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

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

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

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

  7. Java基础之处理事件——使窗口处理自己的事件(Skethcer 1 handing its own closing event)

    控制台程序. 为表示事件的常量使用标识符可以直接启用组件对象的特定事件组.调用组件的enableEvent()方法,并把想要启用事件的标识符传送为参数,但这只在不使用监视器的情况下有效.注册监听器会自 ...

  8. Java基础之处理事件——选项按钮的鼠标监听器(Lottery 2 with mouse listener)

    控制台程序. 定义监听器类有许多方式.下面把监听器类定义为单独的类MouseHandler: // Mouse event handler for a selection button import ...

  9. Java基础之处理事件——applet中语义事件的处理(Lottery 1)

    控制台程序. 语义事件与程序GUI上的组件操作有关.例如,如果选择菜单项或单击按钮,就会生成语义事件. 对组件执行操作时,例如选择菜单项或单击按钮,就会生成ActionEvent事件.在选择或取消选择 ...

随机推荐

  1. Mysql Cluster配置基本篇

    一.下载mysql-cluster 从mysql官网下载对应的mysql-cluster 二.配置管理节点 1.解压mysql-cluster,找到解压文件中的ndb_mgm和ndb_mgmd 2.复 ...

  2. processor, memory, I/O

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION 3.3 INTERCONNECTION S ...

  3. Delphi的哈希表(一)

    哈希表是通过哈希值来访问的,通过一定的内存浪费获取检索速度,在检索项时是不需要逐一检索.在编程中有一定的好处. unit Unit1; interface uses Windows, Messages ...

  4. Bootstrap 进度条媒体对象和 Well 组件

    一.Well 组件 这个组件可以实现简单的嵌入效果. //嵌入效果 <div class="well"> Bootstrap </div> //有 lg 和 ...

  5. pomelo架构概览

    pomelo之所以简单易用.功能全面,并且具有高可扩展性.可伸缩性等特点,这与它的技术选型和方案设计是密不可分的.在研究大量游戏引擎设计思路基础上,结合以往游戏开发的经验,确定了pomelo框架的设计 ...

  6. django internal search

    最近改进了项目中的站内搜索的功能,增加了全文索引,提升了搜索速度.因为项目框架是django,所以采用django+haystack+pyelasticsearch+elasticsearch的方式实 ...

  7. RTSP交互命令简介及过程参数描述

    目录 [hide] 1 RTSP消息格式 2 简单的rtsp交互过程 3 rtsp中常用方法 3.1 OPTION 3.2 DESCRIBE 3.3 SETUP 3.4 PLAY 3.5 PAUSE ...

  8. Magento添加一个下拉登陆菜单Create Magento Dropdown Login in a few minutes

    Dropdown login forms are not a feature many online stores use, but in some cases they could be quite ...

  9. Excel导入数据到Sql server 中出错:“文本被截断,或者一个或多个字符在目标代码页中没有匹配项”

    从Excel导入数据到Sql server 时,由于表中的数据有的很长,导入时出现如下错误(如果数据不是很长,255内以内,则不会出现错误): 出错原因: SQL Server的导入导出为了确定数据表 ...

  10. qt 打开串口 UI卡死

    imx6在qt中打开调试串口时,ui总是会卡死.调试串口已经被文件系统占用,而在qt的app中使用open函数却能够调用open函数,打开成功,造成ui卡死,并且调试串口也卡死.本文记录这个问题的解决 ...