什么是正确的GridbagLayout配置来获得这样的显示?

时间:2014-06-10 16:57:20

标签: java layout-manager gridbaglayout

这是我想要获得的:

expected whole display

我面临的问题与右上角有关:

expected display

使用我的代码,蓝色块绝不会跨越两个绿色块。它被卡在左侧或右侧(取决于我应用的重量,gridx和gridy值保持不变):

actual displayactual display

我有正确的gridx / gridy值,但我无法获得正确的权重。什么是正确的代码?

编辑:这是一个最小的工作示例:

代码:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    frame.add(panel);

    panel.setLayout(new GridBagLayout());

    JLabel score1 = new JLabel("Score1");
    JLabel score2 = new JLabel("Score2");
    JLabel team1 = new JLabel("Team1TestTest");
    JLabel team2 = new JLabel("Team2TestTest");
    JLabel clock = new JLabel("Clock");

    // Layout
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.insets = new Insets(10,10,10,10);
    gbc.anchor = GridBagConstraints.CENTER;

    gbc.weighty = gbc.weightx = 1;

    // First two lines
    gbc.gridy=0;

    // -teams
    gbc.gridx=0;
    gbc.gridheight = 1;
    gbc.gridwidth = 2;
    panel.add(team1,gbc);
    gbc.gridx=2;
    gbc.gridheight = 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    panel.add(team2,gbc);

    // -score 1
    gbc.gridy=1;
    gbc.gridx=0;
    gbc.gridheight = 1;
    gbc.gridwidth = 1;
    panel.add(score1,gbc);
    // -clock
    gbc.gridx=1;
    gbc.gridheight = 1;
    gbc.gridwidth = 2;
    panel.add(clock,gbc);
    // -score 2
    gbc.gridx=3;
    gbc.gridheight = 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    panel.add(score2,gbc);

    frame.setContentPane(panel);
    frame.setVisible(true);
    frame.pack();

    while(true) {}
}
}

结果:

actual MCVE result

1 个答案:

答案 0 :(得分:3)

您可以创建另一个GridBagLayout面板,并将其作为第二行的左侧部分添加到第一个面板中,宽度等于4.

enter image description here