getLocation在java中动态创建的JButtons

时间:2014-03-02 21:27:33

标签: java swing dynamic jbutton null-layout-manager

好的,所以我使用以下代码动态地在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());
        }
    });
}

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

注意我是一个非常新的编程

1 个答案:

答案 0 :(得分:3)

每次运行循环时都会重新定义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对象包含有关事件的信息,其中包括事件源,即您的按钮。