2

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

{|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);

我应该如何改变它以获得预期的结果?

4

1 回答 1

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);
    }
}

输出

在此处输入图像描述

于 2011-07-11T15:23:11.860 回答