Java GridBagConstraints的问题

时间:2011-07-11 15:14:43

标签: java swing gridbaglayout

所以,我需要我的布局看起来像这样:

{|Name|         |Info||Tag||Id|}

现在它看起来像这样:

{|Name|   |Info|   |Tag|   |Id|}

或多或少。这是我的代码:

    GridBagConstraints c;

    c = new GridBagConstraints(0, 0, 5, 1, .5, .1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 5, 5);
    header.add(name, c);
    c = new GridBagConstraints(10, 0, 1, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(id, c);
    c = new GridBagConstraints(8, 0, 2, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(tag, c);
    c = new GridBagConstraints(6, 0, 2, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(info, c);

我应该如何更改以获得所需的结果?

1 个答案:

答案 0 :(得分:6)

水平BoxLayout可能更容易。您的代码将类似于:

header.add( name );
header.add( Box.createHorizontalGlue() );
header.add( info );
...

示例

public class GridBagLayoutTest{

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                createAndShowGUI();             
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        final JPanel panel = new JPanel(){
            @Override
            public Dimension getPreferredSize(){
                return new Dimension(200, 20);
            }
        };
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.add( new JLabel("|Name|"));
        panel.add(Box.createHorizontalGlue());
        panel.add(new JLabel("|Info|"));
        panel.add(new JLabel("|Tag|"));
        panel.add(new JLabel("|Id|"));

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

<强>输出

enter image description here