2012-01-14 83 views
7

新增Java和全新網站。我有一個JLabel添加到BorderLayout的中央面板。我希望JLabel能夠集中在小組中; setAlignmentX似乎可以工作,但setAlignmentY不會(該標籤出現在面板的頂部)。這裏是代碼:setAlignmentY未將JLabel居中放在BorderLayout中

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

JLabel label = new JLabel("This should be centered"); 
label.setAlignmentX(Component.CENTER_ALIGNMENT); 
label.setAlignmentY(Component.CENTER_ALIGNMENT); 
centerPanel.add(label); 

contentPane.add(centerPanel, BorderLayout.CENTER); 

我也試過label.setVerticalAlignment(中心),無濟於事。我在API和Java教程中,在本網站上以及通過谷歌搜索查找了答案。謝謝!

回答

17

你接近,試試這個:

public static void main(String[] args) 
{ 
    JFrame contentPane = new JFrame(); 
    JPanel centerPanel = new JPanel(); 
    centerPanel.setLayout(new BorderLayout()); 

    JLabel label = new JLabel("This should be centered"); 
    label.setHorizontalAlignment(SwingConstants.CENTER); 
    centerPanel.add(label, BorderLayout.CENTER); 

    contentPane.add(centerPanel, BorderLayout.CENTER); 
    contentPane.pack(); 
    contentPane.setVisible(true); 

} 

在Java的GUI編程的許多樂趣之一。我寧願捅我的眼睛,如果我誠實

+2

+1對齊,也可用於構造函數; -0.01眼外傷。 :-) – trashgod 2012-01-14 20:49:12

+1

有沒有辦法保留BoxLayout,在BorderLayout的中間面板中添加到BoxLayout的組件垂直居中? – Jehu 2012-01-14 21:02:06

+0

有一個在這裏閱讀:http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html 我很欣賞它是痛苦的,但我認爲它會幫助你理解,而不是隻是駭客代碼 – 2012-01-14 21:41:40

0

我試圖垂直居中對齊JButton但我有問題,它被拉伸。擺弄後我發現這個作品:

JPanel jpTop = new JPanel(new BorderLayout()); 
jbStop = new JButton("Cancel"); 
JPanel extraPanel = new JPanel(); 
extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.X_AXIS)); 
extraPanel.setAlignmentY(Component.CENTER_ALIGNMENT); 
extraPanel.add(jbStop); 
jpTop .add(extraPanel, BorderLayout.EAST); 

當然,它也適用於JLabel。