简体   繁体   English

动态将按钮添加到JFrame或layeredPane

[英]Adding buttons dynamically to JFrame or a layeredPane

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 );
}

As you can see here, I am creating a chess board in a panel and adding that to a layered pane, which in turn is part of the frame. 如您在这里看到的,我正在面板中创建一个国际象棋棋盘,并将其添加到一个分层的窗格中,该窗格又是框架的一部分。 The idea is to have a menu bar and a couple of buttons to make it all look more presentable. 这个想法是要有一个菜单栏和几个按钮,使它们看起来都更加美观。 But when I try to add the button it captures the entire height of the frame ignoring the dimension I have specified. 但是,当我尝试添加按钮时,它忽略了我指定的尺寸而捕获了框架的整个高度。 I just see one tall button stretching the entire height of the window/frame. 我只看到一个高大的按钮伸展了窗口/框架的整个高度。 What is the mistake here? 这是什么错误? How do I add normal sized buttons dynamically here? 如何在此处动态添加普通大小的按钮? that sits well next to the chessboard? 坐在棋盘旁边好吗?

But when I try to add the button it captures the entire height of the frame ignoring the dimension I have specified. 但是,当我尝试添加按钮时,它忽略了我指定的尺寸而捕获了框架的整个高度。

That is the way BorderLayout.EAST works. 这就是BorderLayout.EAST的工作方式。 Read the section from the Swing tutorial on Using Layout Managers for more information. 阅读Swing教程中有关使用布局管理器的部分,以获取更多信息。

You can always nest layout manager to get your desired look for example: 您总是可以嵌套布局管理器来获得所需的外观,例如:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM