2011-07-11 38 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