好的,所以我使用以下代码在 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());
}
});
}
当我按下“does”按钮时,我希望它打印其在面板上的位置,但它却打印出每次添加的最后一个按钮的位置,请帮忙。
请注意,我是编程新手
最佳答案
每次运行循环时,button
变量都会被重新定义,因此当您最终调用 actionPerformed
方法时,您正在读取最后一个按钮的数据。循环在任何事件发生之前完成,并保存在 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 对象包含有关事件的信息,其中包括事件源,即您的按钮。
关于java - java 中动态创建的 JButton 的 getLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133721/