您的位置:首页 > 编程语言 > Java开发

java核心技术笔记 事件处理

2015-04-19 22:16 639 查看
1. 监听器的一个实例:

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);
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: