2013-07-07 44 views
6

我想將我的JLabel對齊到左側。如何將JLabel對齊到JPanel的左側?

String lText = "<html><b><font color = white face = comic sans ms size = 20>mybook</font></b></html>"; 
    JLabel label = new JLabel(lText); 
    label.setBorder(new EmptyBorder(25,0,25,500)); 

我試圖用EmptyBorder來做,但它沒有正確對齊。我正在使用FlowLayout

回答

5

您可能希望設置JLabel的horizo​​ntalAlignment屬性。一種方法是通過它的構造函數。嘗試:

JLabel label = new JLabel(lText, SwingConstants.LEFT); 

這也可以通過預期的setter方法進行:

label.setHorizontalAlignment(SwingConstants.LEFT); 
+0

這隻會對準標籤的邊界,標籤不如何在面板排列中的文本。 –

13

FlowLayout默認使用CENTER對齊。嘗試使用LEFT對準你JLabelJPanel容器

myJPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); 
+0

這將整個面板對齊到左側。我只想在左側對齊我的標籤。 –

+0

@ArchitVerma:按照答案中的建議,將JLabel放在'JPanel'上,並將這個新的'JPanel'代替你的'JLabel'的當前位置:-)不是嗎? –

+0

即,如果使用'FlowLayout',則需要使用嵌套容器 – Reimeus