2009-12-15 59 views
0

我正在嘗試爲我正在處理的項目繪製一個側欄。我選擇使用GridBagLayout,因爲我對BoxLayout的限制感到沮喪。有人可以幫助解釋我做錯了什麼。我想要的是側邊欄包含兩個JPanel。我將代碼放在邊欄的一半而不是頂部。有人能解釋我在這裏想念什麼嗎?一個帶有GridBagLayout的java側邊欄

JPanel sideBar = new JPanel(); 
    sideBar.setBounds(0, 0, 180, (int)this.getBounds().getHeight()); 
    sideBar.setLayout(new GridBagLayout()); 


    JPanel optionBar = new JPanel(); 
    optionBar.setBorder(BorderFactory.createTitledBorder("Box1")); 
    optionBar.setLayout(new GridBagLayout()); 


    JPanel buttonBar = new JPanel(); 
    buttonBar.setBorder(BorderFactory.createTitledBorder("Options")); 
    buttonBar.setLayout(new GridBagLayout()); 


    GridBagConstraints c = new GridBagConstraints(); 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.gridx = 0; 
    c.ipady = 5; 
    c.insets = new Insets(10,0,0,0); 


    JButton simplify; 
    simplify = new JButton("Open"); 
    simplify.addActionListener(this.listener); 
    c.gridy = 0; 
    buttonBar.add(simplify, c); 

    JButton mergeButton; 
    mergeButton = new JButton("Close"); 
    mergeButton.addActionListener(this.listener); 
    c.gridy = 1; 
    buttonBar.add(mergeButton, c); 

    JButton splitButton; 
    splitButton = new JButton("Merge"); 
    splitButton.addActionListener(this.listener); 
    c.gridy = 2; 
    buttonBar.add(splitButton, c); 

    c.insets = new Insets(0,5,5,5); 
    c.gridy = 0; 
    sideBar.add(optionBar, c); 

    c.gridy = 1; 
    c.ipadx = 70; 
    sideBar.add(buttonBar, c); 

    return(sideBar); 

回答

2

GridBagLayout將只分配組件需要的足夠的垂直空間,其餘空白。我希望你看到你的側杆組件垂直居中?

爲了「推出」組件,您需要設置垂直權重。如果您在最後一個組件上將weighty約束設置爲1.0,則它將佔用該組件的所有剩餘垂直空間,並將其餘部分推到頂部。 (您可能還需要將最後一個面板定位到GridBagConstraints.NORTH)。

嘗試c.weighty = 1.0sideBar.add(buttonBar, c);

0

,我有地方的代碼它們 一半,側邊欄,而不是在 頂部。

那麼您需要閱讀Swing tutorial以瞭解如何正確使用佈局管理器。 BoxLayout比GridBagLayout容易得多,因爲您不必學習如何指定約束。但是,如果您想使用GridBagLayout,請閱讀「如何使用GridBagLayout」一節。你可能想專注於處理「重量和重量」約束的部分。基於我應該幫助解決問題的有限知識。

另外,使用佈局管理器時,不要使用setBounds()或setSize()。

2

如果你熟悉/更舒適的HTML,你可以使用table2gridbag。它是一個小型控制檯工具,它採用佈局描述(HTML表格)並將其轉換爲等效的佈局描述,用於配置GridBagLayout管理器