您好,我正在尝试做一个国际象棋的ratsuk游戏,但仅限于骑士。
import javax.swing.JButton;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Knight {
private Icon image;
private int w;
private int k;
private Random rand;
public Knight() {
image = new ImageIcon(getClass().getResource("redKnight.gif"));
w = rand.nextInt(9);
k = rand.nextInt(9);
}
public void Caballo(JButton[][] matriz, int i, int j) {
matriz[i][j].setIcon(image);
matriz[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute when button is pressed
matriz[i][j].setBackground(Color.RED);
}
});
}
}
所以我试图做一个我不确定是否可行的递归方法。但问题是,在内部addActionListener
,netbeans 告诉我变量必须是最终的,我真的不明白为什么。一旦我运行它,图像根本不显示
这是其余的代码
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.*;
import javax.swing.JPanel;
import java.util.Random;
public class Tablero {
private JButton[][] mesa;
private Random rad;
public Tablero() {
mesa = new JButton[8][8];
}
public void cuadriculado(JFrame ventana) {
JPanel panel = new JPanel(new GridLayout(8, 8, 0, 0));
for (int i = 0; i < mesa.length; i++) {
for (int j = 0; j < mesa[0].length; j++) {
mesa[i][j] = new JButton();
mesa[i][j].setPreferredSize(new Dimension(40, 40));
panel.add(mesa[i][j]);
}
}
for (int r = 0; r < mesa.length; r++) {
for (int t = 0; t < mesa[0].length; t++) {
if (r % 2 == 0 || r == 0) {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.BLACK);
} else {
mesa[r][t].setBackground(Color.WHITE);
}
} else {
if (t % 2 == 0 || t == 0) {
mesa[r][t].setBackground(Color.WHITE);
} else {
mesa[r][t].setBackground(Color.BLACK);
}
}
}
}
ventana.setContentPane(panel);
ventana.setSize(500, 500);
ventana.setVisible(true);
Knight kn =new Knight();
kn.Caballo(mesa, rad.nextInt(9), rad.nextInt(9));
}
}
任何帮助将不胜感激。我对Java真的很陌生,没有人向我解释过这些,所以我一直在苦苦挣扎。