编程动作侦听器的常用方法是什么? [英] What is the common way to program action listeners?

查看:145
本文介绍了编程动作侦听器的常用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习如何使用动作侦听器。根据我的理解,它可以通过以下方式工作:

I just started to learn how to use action listeners. To my understanding it works in the following way:


  1. 默认情况下,有些类包含addActionListener方法(例如按钮的类)。

  1. There are some classes which contains "addActionListener" method by default (for example classes for buttons).

使用此方法,我们向对象添加一个动作侦听器。例如: listenedObject.addActionListener(listeningObject)

Using this method we add an action listener to an object. For example: listenedObject.addActionListener(listeningObject).

当具有listenedObject的操作是执行后,将调用listenObject的actionPerformed方法。所以,这意味着当我们为listenObject编写一个类时,我们需要设置actionPerformed方法。

When an action with the "listenedObject" is performed, the "actionPerformed" method of the "listeningObject" will be called. So, it means that when we program a class for the listeningObject, we need to put there "actionPerformed" method.

我不清楚,我们是否应该为每个想要听的对象创建一个新类。在我看来,这不是一个优雅的解决方案。另一方面,如果我们有一个动作监听器类用于所有(或至少很多)对象,那么我们遇到问题,因为这个类的实例不知道哪个对象正在调用actionPerformed方法(我们需要知道,因为actionPerformed执行的操作因此方法的调用方式而异。)

What is not clear to me, should we create a new class for every object that we want to listen. It does not seem to me as an elegant solution. On the other hand, if we have one action listener class for all (or at least many) object, than we have a problem since a instance of this class will not know which object is calling the "actionPerformed" method (and we need to know that since actions performed by the actionPerformed differs depending on who is called for this method).

在我看来,我们需要创建的每个被监听对象都是个人动作监听器,我们可以通过为动作监听器的相应字段设置特定值来实现。但我不确定这是一个标准的方法吗?人们通常如何做到这一点?

In my opinion, for every listened object we need to create are "personal" action listener and we can do it by setting a specific value to the corresponding field of the action listener. But I am not sure that it is a standard way to go? How do usually people do it?

推荐答案

最常见的处理方法 - 从我个人的经验来看 - 就是简单创建一个匿名内联类。像这样:

The most common way to handle this - judging from my own personal experience - is to simply create an anonymous inline class. Like this:

listenedObject.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        // Your action handling code in here
    }
});

我经常看到人们调用包含listenedObject的对象的方法。例如,在一个带有按钮的Dialog中:

And often I've seen people place a call out to a method of the object containing the listenedObject. For example, in a Dialog that has a button:

myOkayButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        okayButtonPressed();
    }
});

然后在对话框类中:

private void okayButtonPressed() {
    // Do what we need to do
}

这篇关于编程动作侦听器的常用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆