-1
我的actionPerformed方法有问题。每次按下按钮时,我都想更改按钮图像。如果我这样做了一个按钮(button[0][0]
例如)它的工作原理,但我得到了使用数组按下按钮时更改JButton图像
java.lang.ArrayIndexOutOfBoundsException
我被困在这里,我不知道如何解决问题...
public class ExButtons {
JButton[][] button = new JButton[4][5];
ImageIcon[][] img = new ImageIcon[4][5];
ImageIcon cardTurned = new ImageIcon();
private final JPanel panel = new JPanel();
private final JFrame frame = new JFrame();
private int i, j;
public ExButtons() {
img[0][0] = new ImageIcon("...");
img[0][1] = new ImageIcon("...");
img[0][2] = new ImageIcon("...");
img[0][3] = new ImageIcon("...");
img[0][4] = new ImageIcon("...");
img[1][0] = new ImageIcon("...");
img[1][1] = new ImageIcon("...");
img[1][2] = new ImageIcon("...");
img[1][3] = new ImageIcon("...");
img[1][4] = new ImageIcon("...");
img[2][0] = new ImageIcon("...");
img[2][1] = new ImageIcon("...");
img[2][2] = new ImageIcon("...");
img[2][3] = new ImageIcon("...");
img[2][4] = new ImageIcon("...");
img[3][0] = new ImageIcon("...");
img[3][1] = new ImageIcon("...");
img[3][2] = new ImageIcon("...");
img[3][3] = new ImageIcon("...");
img[3][4] = new ImageIcon("...");
cardTurned = new ImageIcon("...");
for (i = 0; i < button.length; i++) {
for (j = 0; j < button[0].length; j++) {
button[i][j] = new JButton(img[i][j]);
}
}
int x = 100, y = 100;
for (i = 0; i < button.length; i++) {
for (j = 0; j < button[0].length; j++) {
button[i][j].setBounds(x, y, 60, 60);
panel.add(button[i][j]);
x += 80;
if (j == 4) {
x = 100;
y += 80;
}
}
}
for (i = 0; i < button.length; i++) {
for (j = 0; j < button[0].length; j++) {
button[i][j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button[" + i + "][" + j + "] was pressed");
button[i][j].setIcon(button[i][j].getIcon() == img[i][j] ? cardTurned : img[i][j]);
}
});
}
}
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(null);
for (i = 0; i < button.length; i++) {
for (j = 0; j < button[0].length; j++) {
panel.add(button[i][j]);
}
}
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new ExButtons().frame.setVisible(true);
}
}
谢谢@JB Nizet! – Nico