我正在制作国际象棋游戏,并且正在使用 JavaSwing 作为 GUI。我遇到的问题是按钮的背景显示不正确。该板由 8x8 个按钮组成,我想要灰色和白色。目前按钮有背景颜色的轮廓,但按钮本身的主要部分是白色的。如何使整个按钮与背景颜色相同?
制作按钮的当前代码:(注意)图像是用另一种方法添加的。 按钮
boardPanel = new JPanel(new GridLayout(8, 8));
boardButtons = new JButton[8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
boardButtons[i][j] = new JButton();
boardButtons[i][j].setPreferredSize(new Dimension(100, 100));
boardButtons[i][j].setMinimumSize(new Dimension(100, 100));
boardButtons[i][j].addActionListener(buttonListener);
if ((i + j) % 2 == 0) {
boardButtons[i][j].setBackground(Color.WHITE);
} else {
boardButtons[i][j].setBackground(Color.GRAY);
}
boardButtons[i][j].setOpaque(true);
boardPanel.add(boardButtons[i][j]);
}
}
// Create a new panel and add the board panel and white space panel to it
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(1200, 800)); // fixed size for board panel
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
contentPane.add(boardPanel);
JPanel whiteSpacePanel = new JPanel();
whiteSpacePanel.setPreferredSize(new Dimension(400, 800)); // desired size of white space
whiteSpacePanel.setBackground(Color.CYAN);
contentPane.add(whiteSpacePanel);
// Add the new panel to the frame and set some properties
setContentPane(contentPane);
setTitle("Capture The Quad Board");
setResizable(false); // prevent resizing of the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
paintBoard();
当前板: