2010-02-03 52 views
1

我有一個似乎沒有道理的擊球手。擺動:BoxLayout和橫向對齊?

如果我運行下面的程序,我會得到兩個對話框,每個對話框都包含JPanel。

alt text alt text

第一個有一對夫婦的JLabel是左對齊。第二個擴展第一個,並添加另一個JPanel作爲子面板,但標籤組是右對齊的(即使在組內它們左對齊)。什麼給,以及如何解決它,使一切都是左對齊? (或者我將如何將它們全部對齊?)

package com.example.test.gui; 

import javax.swing.BorderFactory; 
import javax.swing.BoxLayout; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 

public class BoxLayoutQuestion { 
    public static class TestPanel1 extends JPanel 
    { 
     public TestPanel1() 
     { 
      super(); 
      initTestPanel1(); 
     } 
     void initTestPanel1() 
     { 
      setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 
      add(new JLabel("Four score and seven years ago")); 
      add(new JLabel("One small step for man")); 
      add(new JLabel("To be or not to be, that is the question")); 
     } 
    } 
    public static class TestPanel2 extends TestPanel1 
    { 
     public TestPanel2() 
     { 
      super(); 
      initTestPanel2(); 
     } 
     void initTestPanel2() 
     { 
      JPanel subpanel = new JPanel(); 
      subpanel.setBorder(
        BorderFactory.createTitledBorder("something special")); 
      subpanel.add(new JLabel("Where's the beef?")); 
      add(subpanel); 
     } 
    } 
    public static void main(String[] args) { 
     JOptionPane.showMessageDialog(null, new TestPanel1(), 
       "quotations", JOptionPane.INFORMATION_MESSAGE); 
     JOptionPane.showMessageDialog(null, new TestPanel2(), 
       "more quotations", JOptionPane.INFORMATION_MESSAGE); 
    } 
} 

回答

1

我發現盒子佈局對它包含的組件的對齊非常敏感。 您可能需要爲要添加到對話框的組件設置組件alignmentX。

如果您在添加它們之前對每個組件調用setAlignmentX(LEFT_ALIGNMENT),則應該獲得一致的左對齊行爲。

+0

謝謝,這是訣竅! (+也可以讓我右對齊,如果我喜歡) –

+0

(FWIW,它看起來像你可以先添加它們,然後做setAlignmentX(),並且這也起作用我創建了一個addAligned()方法,以便我可以多次使用它。) –