在 JPanel 中对 JButton 进行排序
Sort JButtons in JPanel
我正在使用 Java 创建一个国际象棋游戏,当我看到 JButtons 没有按顺序添加到 JPanel 时一切正常,也就是说,(0,0) 不在同一个使用 System.out.Println 的位置有谁知道我该如何解决它?
private void configurarCaselles() {
Insets marge = new Insets(0, 0, 0, 0);
for (int i = 0; i < t.getTaulerCaselles().length; i++) {
for (int j = 0; j < t.getTaulerCaselles()[0].length; j++) {
Casella_Grafic c = t.getFitxaGrafic(i, j);
c.setMargin(marge);
ImageIcon icon = new ImageIcon(new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
c.setIcon(icon);
if ((i % 2 == 1 && j % 2 == 1) || (i % 2 == 0 && j % 2 == 0)) {
c.setBackground(Color.WHITE);
} else {
c.setBackground(Color.BLACK);
}
}
}
chessBoard.add(new JLabel(""));
for (int i = 0; i < 8; i++) {
chessBoard.add(new JLabel(COLS.substring(i, i + 1), SwingConstants.CENTER));
}
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
switch (i) {
case 0:
chessBoard.add(new JLabel("" + (9 - (j + 1)), SwingConstants.CENTER));
default:
chessBoard.add(t.getFitxaGrafic(i, j));
}
}
}
}
Icons Extracted here
显然,在将 chessBoard
添加到 chessBoard
:
时,您正在遍历行然后遍历列(从上到下,然后从左到右)的双数组 JButton
chessBoard.add(t.getFitxaGrafic(i, j));
当它应该相反时(列然后行),所以你只需要交换 i
和 j
:
chessBoard.add(t.getFitxaGrafic(j, i));
希望这对您有所帮助。
我正在使用 Java 创建一个国际象棋游戏,当我看到 JButtons 没有按顺序添加到 JPanel 时一切正常,也就是说,(0,0) 不在同一个使用 System.out.Println 的位置有谁知道我该如何解决它?
private void configurarCaselles() {
Insets marge = new Insets(0, 0, 0, 0);
for (int i = 0; i < t.getTaulerCaselles().length; i++) {
for (int j = 0; j < t.getTaulerCaselles()[0].length; j++) {
Casella_Grafic c = t.getFitxaGrafic(i, j);
c.setMargin(marge);
ImageIcon icon = new ImageIcon(new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB));
c.setIcon(icon);
if ((i % 2 == 1 && j % 2 == 1) || (i % 2 == 0 && j % 2 == 0)) {
c.setBackground(Color.WHITE);
} else {
c.setBackground(Color.BLACK);
}
}
}
chessBoard.add(new JLabel(""));
for (int i = 0; i < 8; i++) {
chessBoard.add(new JLabel(COLS.substring(i, i + 1), SwingConstants.CENTER));
}
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
switch (i) {
case 0:
chessBoard.add(new JLabel("" + (9 - (j + 1)), SwingConstants.CENTER));
default:
chessBoard.add(t.getFitxaGrafic(i, j));
}
}
}
}
Icons Extracted here
显然,在将 chessBoard
添加到 chessBoard
:
JButton
chessBoard.add(t.getFitxaGrafic(i, j));
当它应该相反时(列然后行),所以你只需要交换 i
和 j
:
chessBoard.add(t.getFitxaGrafic(j, i));
希望这对您有所帮助。