java核心技术笔记 事件处理
2015-04-19 22:16
639 查看
1. 监听器的一个实例:
2. 作进一步简化,CororAction类只在makeButton方法中使用一次。因此可以将它设计为一个匿名类。
3. 创建包含一个方法调用的监听器。
如果时间监听器调用的方法只包含一个从时间处理器继承来的参数,就可以使用另外一种形式的create方法。例如,调用
等价于
需要将属性source和text的名字转换成方法调用getSource和getText。
4. 适配器类
下面是WindowListener接口:
下面使用窗口适配器:
现在可以将一个Terminator对象注册为事件监听器:
不要就此止步,还可以将监听器类定义为框架的匿名内部类。
ActionListener listener = …; JButton button = new JButton(“OK”); button.addActionListener(listener);
</pre><p>为了实现ActionListener接口,监听器类必须有一个被称为actionPerformed的方法,该方法接受一个ActionEvent对象参数。</p><p></p><pre name="code" class="java">class MyListener implements ActionListener { …. public voidactionPerformed(ActionEvent event) { //reactionto button click goes here …. } }
2. 作进一步简化,CororAction类只在makeButton方法中使用一次。因此可以将它设计为一个匿名类。
public void makeButton(String name, final ColorbackgroundColor) { JButton button= new JButton(name); buttonPanel.add(button); button.addAction:istener(newActionListener() { publicvoid actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } }); }
3. 创建包含一个方法调用的监听器。
loadButton.addActionListener( EventHandler.create(ActionerListener.class,frame,”loadData”));
如果时间监听器调用的方法只包含一个从时间处理器继承来的参数,就可以使用另外一种形式的create方法。例如,调用
EventHandler.create(ActionListener.class,frame,”loadData”,”source.text”)
等价于
newActionListener() { publicvoid actionPerformed(ActionEvent event) { frame.loadData(((JTextField)event.getSource()).getText()); } }
需要将属性source和text的名字转换成方法调用getSource和getText。
4. 适配器类
下面是WindowListener接口:
public interface WindowListener { voidwindowOpened(WindowEvent e); voidwindowClosing(WindowEvent e); void windowClosed(WindowEvent e); …… }<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>
下面使用窗口适配器:
classTerminator extends WindowAdapter { public void windowClosing(WindowEvent e) { if(user agrees) System.exit(0); } }
现在可以将一个Terminator对象注册为事件监听器:
frame.addWindowListener(newTerminator());
不要就此止步,还可以将监听器类定义为框架的匿名内部类。
frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvente) { if(user agrees) System.exit(0); } });
相关文章推荐
- Java核心技术:卷1笔记[6] 事件处理
- #Java 核心技术卷一阅读笔记# 第十一章 事件处理
- 2015 7 3 java核心技术卷一 7-10章 图形,事件处理,Swing组件和应用程序部署
- 事件处理基础 处理按钮点击事件实例 Java核心技术
- Java处理敲击键盘事件 Etch-A-Sketch玩具实现 光标画笔画图程序 Java核心技术
- Java简单图形编辑器 放置、移动和擦除方块 鼠标事件测试程序 Java核心技术 事件处理
- Java 按钮和单击事件映射到动作对象改变面板颜色小程序实例 Java核心技术 事件处理
- Java核心技术(事件处理)
- java核心技术 事件处理
- Java核心技术学习笔记(二)
- 高手Java核心技术学习笔记 http://developer.51cto.com/art/200906/129191.htm
- coco笔记:连续点击相应事件处理(使用协同)_ Java和C#
- Java核心技术学习笔记(三)
- java学习笔记 第二篇 核心技术
- 核心技术笔记之JAVA字符串注意点(2014.04.15_day35)
- 核心技术笔记_重要的java.lang.string:、 String类中的一些重要的方法(2014.04.16 day36)
- Java核心技术笔记——Java的输入输出(2014.04.16~17day36、37)
- Java核心技术 卷1 学习笔记
- Java核心技术学习笔记
- java学习笔记 第二篇 核心技术(二)