2016-10-29 57 views
0

我遇到了一個非常惱人的問題。 JPanel正在增加組件之間的垂直差距,我需要擺脫它。 我試圖讓這個(藍線是我想擺脫的空間):Java如何禁用JPanel組件自動垂直調整大小

enter image description here

看起來像這樣:

enter image description here

這裏是我當前的類:

public class SummaryPanel extends JPanel 
{ 
    private JLabel bagelLabel; 
    private JLabel toppingLabel; 
    private JLabel coffeeLabel; 
    private JLabel shotsLabel; 

    private JLabel subtotal; 
    private JLabel tax; 
    private JLabel total; 

    private JPanel selectionsPanel; 
    private JPanel totalPanel; 

    public SummaryPanel() 
    { 
     bagelLabel = new JLabel("No bagel $0.00"); 
     toppingLabel = new JLabel("No topping $0.00"); 
     coffeeLabel = new JLabel("No coffee $0.00"); 
     shotsLabel = new JLabel("(Includes 0 shots) $0.00"); 

     subtotal = new JLabel(""); 
     tax = new JLabel(""); 
     total = new JLabel(""); 

     setLayout(new GridLayout(2,1)); 

     selectionsPanel = new JPanel(); 

     selectionsPanel.setLayout(new GridLayout(4,1)); 
     selectionsPanel.add(bagelLabel); 
     selectionsPanel.add(toppingLabel); 
     selectionsPanel.add(coffeeLabel); 
     selectionsPanel.add(shotsLabel); 

     totalPanel = new JPanel(); 
     totalPanel.setLayout(new GridLayout(3,1)); 
     totalPanel.add(subtotal); 
     totalPanel.add(tax); 
     totalPanel.add(total); 

     totalPanel.setVisible(false); 

     add(selectionsPanel); 
     add(totalPanel); 
    } 
} 

回答

3

它由佈局管理器控制。

setLayout(new GridLayout(2,1)); 

您正在使用GridLayout,因此兩個組件中的每一個都獲得相同的空間。

selectionsPanel.setLayout(new GridLayout(4,1)); 

繼而每個JLabel獲得每個面板可用總空間的四分之一。當你將組件添加到您使用面板

//setLayout(new GridLayout(2,1)); 
setLayout(new BorderLayout); 

然後:

add(selectionsPanel, BorderLayout.PAGE_START); 
add(totalsPanel, BorderLayout.PAGE_END); 

現在首選大小將受到尊重

相反,你可以使用一個BorderLayout的。

0

GridLayout將把面板分成行數和列數ns指定,並且每個組件將完整填充這些單元格中的一個。

您不妨考慮改爲使用BoxLayout。這將允許您堆疊您的組件,而不會令他們不愉快地擴展。