跨越对象3行的Java Swing GridBagLayout()不起作用

跨越对象3行的Java Swing GridBagLayout()不起作用,java,swing,layout-manager,gridbaglayout,Java,Swing,Layout Manager,Gridbaglayout,我有一个网格布局,每5列5行。我试图跨越我的第一个对象,它是3行5列上的瓷砖面板。它在部分工作 我有第4行和第5行的对象。我希望前3行比第4行和第5行占用更多空间。事实上,空间被均匀地分割到了窗户上。我做错了什么?请参见下面的代码片段和屏幕截图: setLayout(new GridBagLayout()); GridBagConstraints grid = new GridBagConstraints(); // Initialize all the UI components til

我有一个网格布局,每5列5行。我试图跨越我的第一个对象,它是3行5列上的瓷砖面板。它在部分工作

我有第4行和第5行的对象。我希望前3行比第4行和第5行占用更多空间。事实上,空间被均匀地分割到了窗户上。我做错了什么?请参见下面的代码片段和屏幕截图:

setLayout(new GridBagLayout());

GridBagConstraints grid = new GridBagConstraints();


// Initialize all the UI components
tilePanel = new TilePanel(gameModel);

grid.fill = GridBagConstraints.BOTH;

// Grid 5 lines by 5 columns
grid.weightx = 5;
grid.weighty = 5;

// tilePanel takes 3 lines and 5 columns
grid.gridwidth = 5;
grid.gridheight = 3;
grid.gridx = 0;
grid.gridy = 0;
this.add(tilePanel, grid);

// Forth Line       
goal = new JLabel("Goal: " + gameModel.getGameResult());
currentSum = new JLabel("Current sum: 0");
nextButton = new JButton("NEXT");
resetButton = new JButton("RESET");

grid.gridwidth = 1;
grid.gridheight = 1; 

// Forth Line: First column
grid.gridy = 4;
grid.gridx = 0;     
this.add(nextButton, grid);

// Forth Line: Second column
grid.gridx = 1;
this.add(resetButton, grid);


// Firth Line
grid.gridy = 5;

// Firth Line: First column
grid.gridx = 0;
goal.setBorder(new LineBorder(Color.BLACK, 1));
this.add(goal, grid);

// Firth Line: Second column
grid.gridx = 1;
currentSum.setBorder(new LineBorder(Color.BLACK, 1));
this.add(currentSum, grid);

// Firth Line: Third column
grid.gridx = 2;
this.add(new JLabel("TIME"), grid);     

// Firth Line: Fourth column
grid.gridx = 3;
this.add(new JLabel("RESET"), grid);    

// Firth Line: Fifth column
grid.gridx = 4;
this.add(new JLabel("LEVEL"), grid);
窗口截图:

我正在尝试跨越我的第一个对象,它是3行上的瓷砖面板

你不能只说一个组件跨越3条线

任何给定行的高度都由添加到该行的组件的高度确定。如果不向直线添加构件,则该直线没有高度

在您的示例中,您添加了网格为0、4、5的组件。所以在1,2,3的网格中没有组件,所以每个网格的高度都是0

如果每行中都有组件,则只能跨行。因此,如果您添加了5个组件,其中gridy为0、1、2、3、4,那么您可以将第6个组件添加到另一列中,gridy为0,gridheight为3。然后该组件的高度将等于网格0、1和2中组件的高度


如果希望第一行更大,则可以使用ipady值为标题面板提供额外空间。有关所有约束和工作示例的更多信息,请阅读上Swing教程的部分。

权重x和权重y应为浮点值,最小值为0.0,最大值为1.0。值1.0表示获得尽可能多的空间,0.0表示您是最后一个获得额外空间的人。您给出的值为5,可能GridBagLayout正在生成。。。不管它做什么

当添加tilePanel时,我会尝试将weigthx设置为1.0,weighty=0.6,垂直空间的60%,当添加每行剩余的20%垂直空间时,weighty=0.2


但我还没有测试过。

是的,没错!!它工作得很好!谢谢你的解释。文档中的参数不是很清楚,这是一场噩梦。你让我开心!重量只是为了额外的空间。打包框架时,每行将以其首选高度显示。