JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttons = {
"1", "2", "3", "/", "4",
"5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
};
for (int i = 0; i < buttons.length; i++) {
p.add(new JButton(buttons[i]));
add(p);这段代码产生了一个很好的计算器布局,有没有一种方法可以addActionListener到每个按钮,同时保持这个布局,我的意思是不是像这样对每个按钮都这样做。
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// interesting code for button1 goes here
}
});发布于 2012-11-04 23:00:40
我是用这个代码做的..。
String[] buttons = {
"1", "2", "3", "/", "4",
"5", "6", "*", "7", "8", "9", "-", "0", ".", "=", "+"
};
Action[] allActions = new Action[buttons.length];
for ( i = 0; i < buttons.length; i++) {
allActions[i] = new ButtonAction(buttons[i],i);
JButton button = new JButton(allActions[i]);
panel.add(button);
}使用类ButtonAction,如下所示
public class ButtonAction extends AbstractAction
{
int i;
public ButtonAction(String text, int i) {
super(text);
this.i = i;
}
public void actionPerformed(ActionEvent e) {
/* you can put any action here. either make the action depend on array value or
the string text */
System.out.println(i);
}
}发布于 2012-11-04 20:28:08
是的,不是String数组,而是Action实例数组。每个这样的Action都有一个名称,并且也是一个ActionListener。here引用了几个例子。
发布于 2012-11-04 20:30:55
for (int i = 0; i < buttons.length; i++) {
JButton button = new JButton(buttons[i]);
button.addActionListener(new MyAction());
p.add(button);
}哪里
class MyAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent event) {
...
}
}https://stackoverflow.com/questions/13218483
复制相似问题