Java Swing为一组按钮添加鼠标监听器(内部类)导致故障

标签 java arrays swing button mouseevent

好的,所以我要构建的程序很简单。有五个按钮,名称从 0 到 4。如果按下其中任何一个按钮,那么控制台将打印数字 0 到 4。

enter image description here

我使用 GridLayout 将按钮放置在框架中。为了设置每个按钮,我创建了一个方法 inicializarIG()

inicializarIG() 方法创建一个包含 5 个按钮的数组,并在 for 循环中执行以下操作:

  • 为按钮数组中的每个单元格创建一个按钮实例。
  • 为每个按钮设置一个 mouseListener。每个 Listener 中要打印的值是不同的,它由循环的索引决定(我想通过使用索引来实现!)。
  • 将按钮添加到主框架。

令人惊讶的是,这个简单的程序无法正常工作。无论按下什么按钮,它总是打印数字“5”:

enter image description here

注意:我必须将 index var 放在 inicializarIG() 方法之外,以便满足 Listeners 的 var 范围。我不知道这个问题是否相关,只是说因为它可能会有所帮助。

代码:

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;


public class IGrafica {

    private JFrame frame;
    public int index=0;



    public IGrafica(){
        frame = new JFrame();
        configureFrame();
        inicializarIG();

    }

    public void configureFrame(){
        frame.setBounds(100,100,400,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(1,5)); //
    }


    public void inicializarIG(){

        //Buttons

        JButton [] botones = new JButton [5];

        //Loop to set up buttons and add the mouseListener
        for (index = 0; index < botones.length; index++) {
            botones[index] = new JButton(Integer.toString(index));


            //Set up each listener 
            botones[index].addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    System.out.println(index);
                    //texto.setBackground(colores[index]);
                }           
            });

            //Add the button
            frame.getContentPane().add(botones[index]);

        }       
    }



    public void visualizate(){
        frame.setVisible(true);
    }



    public static void main(String[] args) {        
        IGrafica window = new IGrafica();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                window.visualizate();
            }
        });

    }
}

提前致谢。欢迎任何想法。

耶稣

最佳答案

首先,不要为此使用 MouseListener,而是使用 ActionListener,因为这最适合按钮。接下来,你需要记住你的监听器是它自己的一个类,它需要一个自己的变量来存储它自己的索引,否则它会使用循环索引的最终值,这不是你想要的。这或者使用 ActionEvent 的 actionCommand 属性,一个与按钮文本匹配的值。所以:

botones[index].addActionListener(new MyActionListener(index));

// a private inner class
private class MyActionListener implements ActionListener {
    private int index;

    public MyActionListener(int index) {
        this.index = index;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("index is: " + index);
        System.out.println("Action Command is: " + e.getActionCommand());
    }
}

或者如果你想使用匿名内部类:

        botones[index].addActionListener(new ActionListener() {
            private int myIndex;

            {
                this.myIndex = index;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("index is: " + myIndex);
            }
        });

关于Java Swing为一组按钮添加鼠标监听器(内部类)导致故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898192/

相关文章:

java - ExecutorService 和 AtomicInteger : RejectedExecutionException

java - Jsoup 不会替换文档内容

java - 将 Integer[] 转换为 int[] 的最佳方法是什么

c - 'char *' 和 'char (*) [100]' 有什么区别?

java - 从不属于 ButtonGroup 的 JRadioButton 获取文本

java - 检查 JFrame 是否打开

java - 将图像添加到 JFrame 中?

java - 2014 年实现 Java REST Web 服务的最简单框架

java - 如何从 MongoClient, Java 获取连接字符串中指定的 Mongo 数据库

java - 从二维数组中顺序接收元素(Java)