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);
这段代码产生了一个很好的计算器布局是否有一种方法可以将ActionListener 添加到每个按钮,同时保持这个布局我的意思是不要像这样对每个按钮都这样做。
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// interesting code for button1 goes here
}
});