2010-04-01 135 views
10

我有這樣的代碼:如何設置垂直排列的元素之間的距離?

JPanel myPanel = new JPanel(); 
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS)); 

    JButton button = new JButton("My Button"); 
    JLabel label = new JLabel("My label!!!!!!!!!!!"); 

    myPanel.add(button); 
    myPanel.add(label); 

就這樣我與他們之間沒有距離的元素。我的意思是,「頂級」元素總是觸及「底層」元素。我該如何改變它?我想在我的元素之間有一些分離?

我想在我的元素之間添加一些「中間」JPanel(有一些大小)。但我不認爲這是一種獲得理想效果的優雅方式。有人可以幫助我嗎?

回答

13
JPanel myPanel = new JPanel(); 
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS)); 

    JButton button = new JButton("My Button"); 
    JLabel label = new JLabel("My label!!!!!!!!!!!"); 

    myPanel.add(button); 
    myPanel.add(Box.createVerticalStrut(20)); 
    myPanel.add(label); 

將是一種做法。

1

使用Box類作爲不可見的填充元素。 Sun推薦你這樣做。

BoxLayout tutorial

2

您可能想要考慮GridLayout而不是BoxLayout,它具有Hgap和Vgap屬性,可以指定組件之間的常量分離。

GridLayout layout = new GridLayout(2, 1); 
layout.setVgap(10); 
myPanel.setLayout(layout); 
myPanel.add(button); 
myPanel.add(label); 
5

如果你確實打算使用BoxLayout佈局的面板,那麼你應該看看How to Use BoxLayout太陽學習資源,特別是Using Invisible Components as Filler部分。總之,隨着BoxLayout您可以創建作爲您的其他組件之間的間隔特別無形成分:

container.add(firstComponent); 
container.add(Box.createRigidArea(new Dimension(5,0))); 
container.add(secondComponent); 
+1

在這種情況下,你也可以使用Box.createVerticalStrut(5)。還有一個補充性的Box.createHorizo​​ntalStrut(int)。當其中一個維度爲零時,我更喜歡這些。 – 2010-04-01 15:16:05

相關問題