您如何引用其动作侦听器内部的按钮? [英] How do you reference a button inside of its actionlistener?

查看:95
本文介绍了您如何引用其动作侦听器内部的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始习惯于听众,但我还是与他们合作的新手。我需要引用其动作侦听器内部的按钮以获取该按钮的文本。
我想要的代码是:

I'm just starting to get used to listeners but I am still kind of new to working with them. I need to reference a button inside of its actionlistener to get the text of that button. my code I want is:

for(int i = 0; i<48; ++i){
        button[i] = new JButton("");
        contentPane.add(button[i]);
        button[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                x_marks_the_spot();
                if(button[i].getText().equals("X")){
                    increase_hit();
                }
                else{
                    increase_miss();
                }
            }
        });

很明显,我无法执行此操作,因为[i]实际上不存在于码。我敢肯定有一种方法可以通过获取源代码来做到这一点,但我想不到。

Obviously I can't do this because [i] doesn't actually exist in the anon portion of code. I am sure there is a way to do this by getting the source, but I can't think of it.

推荐答案


很显然我不能这样做,因为 [i] 实际上不在代码的匿名部分。

Obviously I can't do this because [i] doesn't actually exist in the anon portion of code.

您可以通过复制 i 转换为 final 变量:

You could do it by copying i into a final variable:

// Make a final copy of loop variable before making the listener
final tmpI = i;
...
// Use your final variable instead of `i` inside the listener
if(button[tmpI].getText().equals("X")){

但这并不是最有效的方法,因为每个按钮都需要自己的侦听器对象,并引用存储在代码中的 tmpI

However, this is not the most efficient way of doing it, because each button would need its own listener object, with the reference to tmpI stored inside the code.

您可以创建一个 ActionListener 对象,并在所有按钮之间共享它,如下所示:

You can create a single ActionListener object, and share it among all buttons, like this:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        x_marks_the_spot();
        JButton sender = (JButton)e.getSource();
        if(sender.getText().equals("X")){
            increase_hit();
        } else{
            increase_miss();
        }
    }
};
for(int i = 0; i<48; ++i){
    button[i] = new JButton("");
    contentPane.add(button[i]);
    button[i].addActionListener(listener);
}

这篇关于您如何引用其动作侦听器内部的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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