我正在尝试使用Swing在Java中创建一个简单的计算器,并且已经通过以下方式创建了按钮:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
我的问题是如何引用事件处理程序中的每个特定按钮?我想不出一种方法,而不必手动创建每个按钮而不是使用循环。
谢谢。
最佳答案
在您的侦听器中,调用event.getSource()
,这将返回已按下的按钮。获取按钮的文本,您就会得到它的编号。
或为每个按钮创建一个不同的处理程序实例,然后将按钮的值(i
)传递给处理程序的构造函数。最后一种解决方案是IMO,因为它不依赖于按钮的文本,因此更干净。例如,如果您用图像替换了文本,则第一种技术将不再起作用。
关于java - 如何从使用循环创建的按钮获取输入?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22610157/