java面板占用相同的空间
我有两个面板。第一个看起来像这样
public class BoardPanel extends JPanel
{
public BoardPanel()
{
setLayout(null);
this.setOpaque(false);
Button button = new JButton("..");
button.setLocation(...);
button.setSize(...);
add(button);
}
public void paintComponent( Graphics g )
{
/*
* Painting some stuff here.
*/
}
}
另一个面板是这样的:
public class OtherPanel extends JPanel
{
public OtherPanel()
{
super();
this.setLayout(null);
this.setOpaque(false);
JPanel panel1 = new JPanel();
panel1.setLocation(...);
panel1.setSize(...);
panel1.setOpaque( .. );
JPanel panel2 = new JPanel();
panel2.setLocation(...);
panel2.setSize(...);
panel2.setOpaque( .. );
add(panel1):
add(panel2);
}
}
在那之后,我把我的两个面板放在一个框架里。但我希望我的面板比其他面板占据更多的屏幕。所以我用GridBagLayout作为框架
public class MainFrame extends JFrame
{
private GridBagLayout aGridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public MainFrame()
{
super("Quoridor");
setLayout(gridLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
this.getContentPane().setBackground(Color.decode("#b2a6a6"));
BoardPanel boardPanel = new BoardPanel();
OtherPanel otherPanel = new OtherPanel();
this.addComponent(boardPanel, 1, 1, 2, 1);
this.addComponent(otherPanel, 1, 3, 1, 1);
}
public void addComponent(Component component , int row , int column , int width
, int height)
{
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
aGridLayout.setConstraints(component, constraints);
add(component);
}
}
问题是,框架为两个面板提供了相等的空间,而没有为板面板提供更多的空间。 为什么会这样?这和面板的边界有关系吗
# 1 楼答案
下面是一个关于GridBagLayout的好教程:https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html。另请参见下面的代码和屏幕截图。“定位点”字段将零部件定位在第一条直线上。weightx字段为boardPanel的列提供了更多空间。ipady字段指定要添加到构件高度的量。在这里,boardPanel获得了大部分宽度和所有高度。另一个面板获得一半的高度