【发布时间】:2021-04-01 18:42:27
【问题描述】:
我正在尝试创建一个棋盘,但由于某种原因它不起作用。
final int HEIGHT = 600;
final int WIDTH = 800;
final int ROW = 8;
final int COL = 8;
String COLS = "ABCDEFGH";
JFrame frame = new JFrame();
JPanel chessBoard = new JPanel();
JButton[][] chessSquares = new JButton[ROW+1][COL+1];
public void initializeGUI() {
frame.setSize(WIDTH, HEIGHT);
frame.setTitle("Chess");
chessBoard.setLayout(new GridLayout(ROW, COL));
//Creating the chessboard without the pieces
JButton temp;
for(int row=1; row<=8; row++) {
for(int col=1; col<=8; col++) {
chessSquares[row][col] = new JButton("row: " + row + "col : " + col);
if ((row+col) % 2 != 0) {
temp = chessSquares[row][col];
temp.setBackground(Color.black);
chessBoard.add(temp);
}
else {
temp = chessSquares[row][col];
temp.setBackground(Color.white);
chessBoard.add(temp);
}
}
}
frame.add(chessBoard);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
这是它的样子:
不起作用的事情列表:
- 有些方块不是黑色的。
- 棋盘占据了 GUI 的整个空间。 (我希望棋盘占用更少的空间。我尝试使用 BorderLayout.South 但它没有显示整个边框,因为它不可调整大小。)
注意 * row 和 cols 的打印只是为了以后帮助我。不是董事会的一部分。不影响棋盘的颜色(我试过了)
编辑:将 setOpaque 设置为 true 后,我明白了。
有没有办法让整个按钮变黑?
【问题讨论】:
-
发布的代码对我有用。在线运行here。如果它不适合您,您将不得不提供更多信息。旁注: 1.
new JButton[ROW+1][COL+1]太大。使用new JButton[ROW][COL]2. 将循环从 `for(int row=1; row -
@c0der 我需要将它保留在 ROW+1 和 COL+1 以便更轻松地处理事件。我正在制作一个棋盘,其中行和列从 1 开始。另外,我正在使用 MAC。
标签: java swing user-interface jpanel jbutton