2013-10-10 25 views
0

我想用許多JLabel填充JPanel GridLayout。但是,我希望每個LabelText具有相同的像素寬度。標籤全部有2個部分:如何在JLabel中創建固定的「物理」長度字符串

VarA:  123.4 
VarB:  Green 
DateMax 12/03/13 

我可以使用等寬字體完成此操作,因爲我只需要計算總字符數。

有沒有辦法爲TrueType字體做同樣的事情?

+0

我不認爲可以左鍵調整標籤的一部分文字,然後右鍵調整另一部分。但是你可以使用兩個標籤來實現它。爲什麼不建立你自己的組件呢? – Steinar

回答

0

如何做到這一個小例子:

public class AdjustedLabel extends JPanel { 

    public AdjustedLabel(String leftText, String rightText) { 
     JLabel leftLabel = new JLabel(leftText, SwingConstants.LEFT); 
     JLabel rightLabel = new JLabel(rightText, SwingConstants.RIGHT); 
     setLayout(new BorderLayout()); 
     add(leftLabel, BorderLayout.WEST); 
     add(rightLabel, BorderLayout.EAST); 
    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame("label testing"); 
     JPanel panel = new JPanel(new GridLayout(3, 1)); 
     panel.add(new AdjustedLabel("VarA:", "123.4")); 
     panel.add(new AdjustedLabel("VarB:", "Green")); 
     panel.add(new AdjustedLabel("DateMax:", "12/03/13")); 
     frame.setContentPane(panel); 
     frame.setSize(200, 100); 
     frame.setVisible(true); 
    } 
} 

編輯:一些調整,使組件更地道。

+0

這樣做的工作!我永遠都不會想到它。 – ManInMoon

相關問題