场景:我有一系列 jbutton(在运行时创建),每个 jbutton 的标签中都有一个数字。按钮是使用以下代码创建的:
for (int i = 1; i <= tablesNumber; i++) {
JButton button = new JButton(Integer.toString(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Orders().setVisible(true);
}
});
jPanel1.add(button);
}
我需要将触发事件的按钮的编号传递给 Orders 类,例如如果用户单击 5 号按钮,我需要将值 5 传递给 Orders。 我怎样才能做到这一点? 谢谢。
最佳答案
根据你的问题:
pass to the class Orders the number of the button which fires the event
您可以捕获循环迭代变量i
,以便可以在匿名事件处理程序中使用它。为了便于论证,我假设您想要将数字传递到构造函数中,但您可以随意使用它:
for (int i = 1; i <= tablesNumber; i++) {
final int t = i; // <-- NEW LINE HERE
JButton button = new JButton(Integer.toString(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Orders(t).setVisible(true); // <-- USE t here however you need to
}
});
jPanel1.add(button);
}
如果没有final int t = i
,您可能会收到编译器错误“无法在不同方法中定义的内部类中引用非final变量i”。这是因为捕获变量(即匿名类方法内使用的外部作用域的变量必须是 final
(或实际上是 Final - 从 SE 8 开始,此行为已略有变化)。
关于java - 如何将值从按钮传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23855779/