2014-01-30 119 views
0

默認JLabel在其邊界的中間繪製其文本。例如,如果標籤的height是20,font height是14,則Y座標將是(20 - 14)/2 = 3。就像這樣:JLabel text Y繪製座標

Red line is the JLabel bounds

,我應該怎麼做,如果要對齊文本到JLabelboundsTOP?就像這樣:

Red line is the JLabel bounds

UPD:

public class LabelTest extends JFrame { 

    public LabelTest() { 
     setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     setSize(500, 500); 

     setLocationRelativeTo(null); 

     JPanel contentPanel = new JPanel(); 
     contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS)); 

     contentPanel.add(Box.createHorizontalStrut(10)); 

     final JLabel label1 = new JLabel("JLabel"); 
     label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help 
     label1.setBorder(BorderFactory.createLineBorder(Color.RED)); 
     label1.setFont(new Font("Arial", Font.PLAIN, 14)); 
     contentPanel.add(label1); 

     setContentPane(contentPanel); 

     setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new LabelTest(); 
      } 
     }); 
    } 
} 

回答

1

與往常一樣,API是你最好的朋友:根據您的更新SSCCE http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setVerticalAlignment(int)

編輯 - ,問題是,你的BoxLayout會縮小JLabel的大小,所以垂直文本位置並不重要。嘗試使用BorderLayout來檢查。

問題是JLabel的插頁在JLabel的頂部和底部添加了一個小空間,所以即使它位於頂部,文本看起來居中。這裏有一個解決插入問題:How to change gap in swing label

+0

謝謝,但沒有,它並不能幫助。 – SeniorJD

+0

我寫過* label1.setVerticalAlignment(SwingConstants.TOP)*,但我仍然看到JLabel與附加的第一張圖片相似。 – SeniorJD

+0

然後你需要發佈一個[SSCCE](http://sscce.org)來證明你所做的事情,因爲setVerticalAlignment()方法完全適合我。 –

2

你應該是pack框架。如果你這樣做,那麼應該在標籤中沒有未使用的空間。如果你想空的空間,使用空邊境

label.setBorder(new EmptyBorder(0, 0, 5, 0)); 

          top, left, bottom, right 

而且,不設置大小,使用佈局曼格斯,讓他們爲你做的大小。設置大小會給你。設置尺寸會給你一個嚴格的外觀,可能在不同的平臺上看起來和表現不同。佈局管理器將允許您的GUI更加流暢和適應不同的環境。

有關更多信息,請參見Laying out Components Within a Container與佈局

工作還看到Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?


+0

謝謝,它可以幫助我。順便說一句,最好使用'BorderFactory'而不是'EmptyBorder'手工創建。恕我直言;) – SeniorJD

+0

有什麼區別?這只是一個便利的課程,但也是一樣的,不是嗎? –

+0

就是這樣。我的意思是方便。 – SeniorJD