控制台程序。

定义事件监听器的类必须实现监听器接口。所有的事件监听器接口都扩展了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. PHP文件操作 之统计目录大小

    <?php //定义一个函数 统计目录大小函数 function dirSize($dirName) { //判断目录是否存在 if (!file_exists($dirName)) { die ...

  2. 20145317彭垚 java课程总结

    课程总结 每周读书笔记链接汇总 第一周http://www.cnblogs.com/5317p/p/5248481.html 第二周http://www.cnblogs.com/5317p/p/527 ...

  3. MYSQL PASSWORD()

    https://www.pythian.com/blog/hashing-algorithm-in-mysql-password-2/ SELECT PASSWORD ("this_is_a ...

  4. [转]SQLBulkCopy使用

    SQLBulkCopy,用于数据库之间大批量的数据传递.通常用于新,旧数据库之间数据的更新.即使表结构完全不同,也可以通过字段间的对应关系,顺利的将数据导过来. 首先,SQLBulkCopy需要2个连 ...

  5. OpenGL完全教程 第一章 初始化OpenGL

    第一章 初始化OpenGL 无论是什么东西,要使用它,就必须对它进行初始化.如果你之前使用过GDI,你应该也多多少少了解到GDI在绘制图形之前要为之创建渲染环境.OpenGL也一样.本章给出的代码,大 ...

  6. JS之Array.slice()方法

    1.Array.slice(startIndex,endIndex); 返回由原始数组从startIndex到endIndex-1的元素构成的新数组; startIndex:默认值0,如果startI ...

  7. Sql Server中通配符

    Sql Server中通配符的使用 通配符_ "_"号表示任意单个字符,该符号只能匹配一个字符."_"可以放在查询条件的任意位置,且只能代表一个字符.一个汉字只 ...

  8. php保存远程文件到本地的方法

    用到了ob_start();<?php header("Content-type:text/html charset=utf-8"); if(!empty($_POST['p ...

  9. 配置maven环境

    第一步:安装maven,安装maven最简单,直接将maven的解压文件放入本地某目录下即可,无需手动安装 第二步:eclipse中导入maven项目后,会后错,或maven无法使用,则需要进行mav ...

  10. python 内容查询小助手

    点我,点我,python os.path  模块: 点我,点我,Python logging模块详解 点我,点我,python两个 list 获取交集,并集,差集的方法 点我,点我,python,my ...