gpt4 book ai didi

java - 棋盘按钮的背景未设置为黑色

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:23 25 4
gpt4 key购买 nike

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChessBoardGUI extends JFrame {

private Container contents;
private JButton[][] squares = new JButton[8][8];
private Color colorBlack = Color.BLACK;

private int row = 7;
private int col = 1;

private ImageIcon knight = new ImageIcon("knight.jpg");

public ChessBoardGUI() {
super("GUI GridLayout Manager - (click a valid square to move knight)");

contents = getContentPane();
contents.setLayout(new GridLayout(8,8));

ButtonHandler buttonHandler = new ButtonHandler();

for (int i = 0; i < 8; i++) {

for (int j = 0; j < 8; j++) {

squares[i][j] = new JButton();
if ((i + j) % 2 != 0) {

squares[i][j].setBackground(colorBlack);
}
contents.add(squares[i][j]);
squares[i][j].addActionListener(buttonHandler);
}
}
squares[row][col].setIcon(knight);

setSize(500, 500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}

private boolean isValidMove(int i, int j) {
int rowDelta = Math.abs(i - row);
int colDelta = Math.abs(j - col);

if ((rowDelta == 1) && (colDelta == 2)) {
return true;
}
if ((colDelta == 1) && (rowDelta == 2)) {
return true;
}
return false;

}

private void processClick(int i, int j) {
if (isValidMove(i, j) == false) {
return;
}
squares[row][col].setIcon(null);
squares[i][j].setIcon(knight);
row = i;
col = j;
}

private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (source == squares[i][j]) {
processClick(i, j);
return;
}
}
}
}
}

public static void main(String args[]) {
ChessBoardGUI gui = new ChessBoardGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}

}

我有一个创建棋盘 GUI 的程序,但是当我运行代码时,按钮都是白色的,而不是黑白按钮(就像棋盘一样)。谁能告诉我我哪里做错了?任何帮助表示赞赏!当我运行程序时,我看到的只是一个带有白色按钮的窗口,但没有黑色按钮。

最佳答案

在我的代码中,我添加了 setOpaque() 方法,但黑色仅在边框处,所以我添加了这行代码:

  squares[i][j].setBorder(null);

代码如下:

 if ((i + j) % 2 != 0) {

squares[i][j].setBackground(colorBlack);
squares[i][j].setBorder(null);
squares[i][j].setOpaque(true);
}

关于java - 棋盘按钮的背景未设置为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53817286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com