在java中动态创建的JButtons上的getLocation



好的,所以我使用以下代码在 J 面板上动态地制作了一行具有空布局的 J 按钮:

int Y = 100;
int X = 100;
for(x=1, x<=20, x++){
    button = new JButton(x);
    button.setLayout(null);
    button.setSize(100, 100);
    button.setLocation(X,Y);
    button.setVisible(true);
    panel.add(button); 
    X += 100;
    //action listener
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //should print out the location of the button that was clicked
            System.out.println(button.getLocation());
        }
    });
}

当我按下 Do 按钮时,我希望它在面板上打印其位置,但它打印出每次添加的最后一个按钮的位置,请帮助。

请注意,我对编程很陌生

每次运行循环时都会重新定义button变量,因此当您最终调用actionPerformed方法时,您正在读取最后一个按钮的数据。循环在任何事件发生之前完成,并保存了在 button 变量中创建的最后一个按钮的引用。

您需要从事件对象引用button,因为它包含对作为事件源的按钮的引用:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //should print out the location of the button that was clicked
        System.out.println( ((JButton)e.getSource()).getLocation() );
    }
});

addActionListener 方法调用 20 次,但 actionPerformed 方法以异步方式调用,并且仅在发生操作事件(例如:按钮单击)时调用。ActionEvent 对象包含有关事件的信息,其中包括事件的源,即按钮。

最新更新