我有一个 GridBagLayout 每 5 列 5 行。我试图跨越我的第一个对象,它是 3 行和 5 列上的 TilePanel。它部分工作。
我有第 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);
窗口截图:
weightx 和 weighty 应该是浮点值,最小值为 0.0,最大值为 1.0。值 1.0 表示“获得尽可能多的空间”,而 0.0 表示“您是最后一个获得额外空间的人”。您给出的值为 5,并且可能 GridBagLayout 正在制作......无论它制作什么。
我会尝试在添加 tilePanel 时将 weigthx 设置为 1.0 和 weighty=0.6(垂直空间的 60%),在添加其余部分(每行垂直空间的 20%)时将 weighty=0.2 设置为。
但我没有测试过。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句