2011-07-11 37 views
2

所以,我需要我的布局,看起来像这样:问题与Java的GridBagConstraints

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

我应该如何改变这个来得到想要的结果?

回答

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

+0

+1,我的想法完全吻合。 – mre

+0

如果你觉得我提供的示例是不能令人满意的,随意删除编辑。我认为这可能会丰富你已经正确的答案。 :) – mre

+0

对,伙计。 – MirroredFate