public ChessGameDemo(){
Dimension boardSize = new Dimension(600, 600);
// Using a Layered Pane
layeredPane = new JLayeredPane();
add(layeredPane);
layeredPane.setPreferredSize(new Dimension(700,700));
//Create a reset button that will reset the game
JButton button = new JButton("Reset");
button.setPreferredSize(new Dimension(50,50));
add(button,BorderLayout.EAST);
//Add the chessboard to the Layered Pane
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );
int row = (i / 8) % 2;
if (row == 0)
square.setBackground( i % 2 == 0 ? Color.blue : Color.white );
else
square.setBackground( i % 2 == 0 ? Color.white : Color.blue );
}
正如您在此处看到的,我正在面板中创建一个棋盘并将其添加到分层窗格中,而分层窗格又是框架的一部分。这个想法是有一个菜单栏和几个按钮,让它看起来更漂亮。但是当我尝试添加按钮时,它会捕获框架的整个高度,而忽略我指定的尺寸。我只看到一个高大的按钮延伸了窗口/框架的整个高度。这里有什么错误?如何在这里动态添加正常大小的按钮?放在棋盘旁边好吗?