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 );
}
正如您在此处所看到的,我正在面板中创建一个棋盘并将其添加到分层 Pane 中,而分层 Pane 又是框架的一部分。我们的想法是有一个菜单栏和几个按钮,让一切看起来更漂亮。但是,当我尝试添加按钮时,它会捕获框架的整个高度,忽略我指定的尺寸。我只看到一个高按钮拉伸(stretch)了窗口/框架的整个高度。这里有什么错误呢?如何在这里动态添加正常大小的按钮?就在棋盘旁边吗?
最佳答案
But when I try to add the button it captures the entire height of the frame ignoring the dimension I have specified.
这就是 BorderLayout.EAST 的工作方式。阅读 Swing 教程中关于 Using Layout Managers 的部分了解更多信息。
您始终可以嵌套布局管理器以获得所需的外观,例如:
JPanel east = new JPanel( new BorderLayout() );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
east.add(buttons, BorderLayout.NORTH);
buttons.add( button1 );
buttons.add( button2 );
frame.add(east, BorderLayoutEAST);
关于java - 动态添加按钮到 JFrame 或 LayeredPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18882353/