控制台程序。

定义事件监听器的类必须实现监听器接口。所有的事件监听器接口都扩展了java.util.EventListener接口。这个接口没有声明任何方法,仅仅用于表示监听器对象。使用EventListener类型的变量可以保存任意事件监听器对象的引用。

要为特定的事件类型实现监听器,只需要实现对应接口中的方法即可。让应用程序类成为窗口事件的监听器,就可以处理SketcherFrame窗口的一些窗口事件。接下来必须创建Sketcher对象,作为事件的监听器。

 // Main window for the Sketcher application
import javax.swing.*;
import static java.awt.event.InputEvent.*; // For modifier constants @SuppressWarnings("serial")
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title) {
setTitle(title); // Set the window title
setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(menuBar); // Add the menu bar to the window JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut // Construct the file drop-down menu
newItem = fileMenu.add("New"); // Add New item
openItem = fileMenu.add("Open"); // Add Open item
closeItem = fileMenu.add("Close"); // Add Close item
fileMenu.addSeparator(); // Add separator
saveItem = fileMenu.add("Save"); // Add Save item
saveAsItem = fileMenu.add("Save As..."); // Add Save As item
fileMenu.addSeparator(); // Add separator
printItem = fileMenu.add("Print"); // Add Print item // Add File menu accelerators
newItem.setAccelerator(KeyStroke.getKeyStroke('N',CTRL_DOWN_MASK ));
openItem.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK));
saveItem.setAccelerator(KeyStroke.getKeyStroke('S', CTRL_DOWN_MASK));
printItem.setAccelerator(KeyStroke.getKeyStroke('P', CTRL_DOWN_MASK)); // Construct the Element drop-down menu
elementMenu.add(lineItem = new JRadioButtonMenuItem("Line", true));
elementMenu.add(rectangleItem = new JRadioButtonMenuItem("Rectangle", false));
elementMenu.add(circleItem = new JRadioButtonMenuItem("Circle", false));
elementMenu.add(curveItem = new JRadioButtonMenuItem("Curve", false));
ButtonGroup types = new ButtonGroup();
types.add(lineItem);
types.add(rectangleItem);
types.add(circleItem);
types.add(curveItem); // Add element type accelerators
lineItem.setAccelerator(KeyStroke.getKeyStroke('L', CTRL_DOWN_MASK));
rectangleItem.setAccelerator(KeyStroke.getKeyStroke('E', CTRL_DOWN_MASK));
circleItem.setAccelerator(KeyStroke.getKeyStroke('I', CTRL_DOWN_MASK));
curveItem.setAccelerator(KeyStroke.getKeyStroke('V', CTRL_DOWN_MASK)); elementMenu.addSeparator();
JMenu colorMenu = new JMenu("Color"); // Color submenu
elementMenu.add(colorMenu); // Add the submenu
colorMenu.add(redItem = new JCheckBoxMenuItem("Red", false));
colorMenu.add(yellowItem = new JCheckBoxMenuItem("Yellow", false));
colorMenu.add(greenItem = new JCheckBoxMenuItem("Green", false));
colorMenu.add(blueItem = new JCheckBoxMenuItem("Blue", true)); // Add element color accelerators
redItem.setAccelerator(KeyStroke.getKeyStroke('R', CTRL_DOWN_MASK));
yellowItem.setAccelerator(KeyStroke.getKeyStroke('Y', CTRL_DOWN_MASK));
greenItem.setAccelerator(KeyStroke.getKeyStroke('G', CTRL_DOWN_MASK));
blueItem.setAccelerator(KeyStroke.getKeyStroke('B', CTRL_DOWN_MASK)); menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
} private JMenuBar menuBar = new JMenuBar(); // Window menu bar // File menu items
private JMenuItem newItem, openItem, closeItem,
saveItem, saveAsItem, printItem; // Element menu items
private JRadioButtonMenuItem lineItem, rectangleItem, circleItem, // Types
curveItem, textItem;
private JCheckBoxMenuItem redItem, yellowItem, // Colors
greenItem, blueItem ;
}

快捷键是一种唯一的组合键,用于直接通过键盘选择菜单栏上的菜单以显示下拉菜单。setMnemoric()方法的作用是实现快捷键,并在菜单项标签中为快捷键字母加上下划线。菜单栏上每个菜单项的快捷键都必须是唯一的组合键。Windows中的典型快捷键是Alt键加菜单项标签中的大写字母。

加速键也是一种组合键,按下这种组合键,就可以直接从下拉菜单中选择菜单项,而不必先显示下拉菜单。在Windows下,Ctrl键常常和大写字母组合使用,作为菜单项的加速键。要为菜单项定义加速键,应调用封装了菜单项的对象的setAccelerator()方法。例如,对于Line菜单项,可以编写如下代码:

lineItem.setAccelerator(KeyStroke.getKeyStroke('L',InputEvent.CTRL_DOWN_MASK));

javax.swing.KeyStroke类定义了组合键。KeyStroke类中的静态方法getKeyStroke()返回对应于参数的KeyStroke对象。第一个参数是组合键中的字母,第二个参数指定一个或多个修饰键。只有大写字母才能用于表示组合键中的字母,小写字母会选择非字母键,例如数字小键盘和功能键。修饰符被指定为java.awt.event包中的InputEvent类所定义的单比特(single-bit)常量。InputEvent类定义的常量标识了键盘上的控制键和鼠标按钮。

 // Sketching application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; public class Sketcher implements WindowListener {
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(this); // theApp as window listener
window.setVisible(true);
} // Handler for window closing event
public void windowClosing(WindowEvent e) {
window.dispose(); // Release the window resources
System.exit(0); // End the application
} // Listener interface methods you must implement -but don't need
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {} private SketcherFrame window; // The application window
private static Sketcher theApp; // The application object
}

建立窗口组件后,createGUI()方法就调用窗口对象的addWindowListener()方法。addWindowListener()方法的参数是对接受窗口事件的监听器对象的引用,这里是变量this,表示应用程序对象theApp。如果其他监听器对象要注册为接受这个事件,只需要添加对addWindowListener()方法的更多调用,对每个监听器调用一次即可。

在Sketcher类中实现WindowListener接口时,必须实现这个接口声明的所有7个方法。否则类就是抽象的,就不能创建Sketcher类型的对象。这里只有windowClosing()方法包含代码,其他方法的方法体都是空的,因为不需要它们。

Java基础之处理事件——实现低级事件监听器(Sketcher 2 implementing a low-level listener)的更多相关文章

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

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

  2. Java基础之处理事件——使用动作Action(Sketcher 6 using Action objects)

    控制台程序. 动作Action是任何实现了javax.swing.Action接口的类的对象.这个接口声明了操作Action对象的方法,例如,存储与动作相关的属性.启用和禁用动作.Action接口扩展 ...

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

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

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

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

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

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

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

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

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

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

  8. Java学习笔记(二)事件监听器

    Java实现对组件事件(如单击.输入等)的监听和JavaScript类似,都是先添加Listener,再写触发函数,不同的是,Java实现监听前必须使用implements将各个接口添加到类内. 相关 ...

  9. Java基础——Servlet(七)过滤器&监听器 相关

    一.过滤器简介 Filter 位于客户端和请求资源之间,请求的资源可以是 Servlet Jsp html (img,javascript,css)等.用于拦截浏览器发给服务器的请求(Request) ...

随机推荐

  1. 【翻译】Kinect v1和Kinect v2的彻底比较

      本连载主要是比较Kinect for Windows的现行版(v1)和次世代型的开发者预览版(v2),以C++开发者为背景介绍进化的硬件和软件.本文主要是对传感的配置和运行条件进行彻底的比较.   ...

  2. QT5中文显示

  3. ContentType Office

    Office对应ContentType 当从浏览器返回一个文件时,需要指定ContentType,以下是Office2007对应的值: "application/vnd.openxmlfor ...

  4. svn local obstruction, incoming add upon merge

    http://little418.com/2009/05/svn-local-obstruction-incoming-add-upon-merge.html If you've found this ...

  5. memcached使用详解

    不错的文章 http://www.ttlsa.com/memcache/memcached-description/

  6. A BRIEF HISTORY OF COMPUTERS

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION Vacuum Tubes   Transi ...

  7. 不绑架输入--document.getElementById("linkage_"+id_type+"_echo").value="";--联动

    <script> function w_linkage(id_type) { var selected = $("#linkage_"+id_type+"_t ...

  8. 【转】JavaScript中的this关键字使用的四种调用模式

    http://blog.csdn.net/itpinpai/article/details/51004266 this关键字本意:这个.这里的意思.在JavaScript中是指每一个方法或函数都会有一 ...

  9. Mars 是微信官方的终端基础组件,是一个使用 C++ 编写的业平台性无关的基础组件

    http://www.oschina.net/p/wechat-mars http://www.oschina.net/news/80453/wewechat-open-source-plan

  10. ASP.NET中 WebForm 窗体控件使用及总结【转】

    原文链接:http://www.cnblogs.com/ylbtech/archive/2013/03/06/2944675.html ASP.NET中 WebForm 窗体控件使用及总结. 1.A, ...