java核心技术笔记 事件处理

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);
              }
       });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值