JmJ*_*JmJ 0 java swing jbutton actionlistener
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何引用事件处理程序中的每个特定按钮?我无法想到一种方法来做到这一点,而无需手动创建每个按钮而不是使用循环.
谢谢.
在你的监听器中,调用event.getSource(),这将返回已按下的按钮.获取按钮的文本,您就有了它的编号.
或者为每个按钮创建一个不同的处理程序实例,并将button(i)的值传递给处理程序的构造函数.最后一个解决方案是更清洁,IMO,因为它不依赖于按钮的文本.例如,如果您用图像替换文本,则第一种技术将不再起作用.
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |