你如何在它的动作监听器中引用一个按钮?

How do you reference a button inside of its actionlistener?

我才刚刚开始习惯听众,但我对与他们共事还是有点陌生​​。我需要在其动作监听器中引用一个按钮来获取该按钮的文本。 我想要的代码是:

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] 实际上并不存在于代码的匿名部分。我确信有一种方法可以通过获取源代码来做到这一点,但我想不出。

do this by getting the source

我相信你想要的是ActionEvent.getSource()

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

您可以通过将 i 复制到 final 变量中来实现:

// 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 的引用。

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

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);
}