2016-02-26 153 views
-1

爲此示例定義默認值的最佳方式是什麼,因此我不必再爲每個對象定義邊框和字體。爲JLabel定義默認值

Border infoLabelMargin = new EmptyBorder(10, 10, 10, 10); 

JLabel usernameInfoLabel = new JLabel("Benutzer: " + GlobalValues.USERNAME); 
Border usernameInfoLabelBorder = usernameInfoLabel.getBorder(); 
usernameInfoLabel.setFont(new Font("SANS_SERIF", Font.BOLD, 35)); 
usernameInfoLabel.setBorder(new CompoundBorder(usernameInfoLabelBorder, infoLabelMargin)); 
infoBox.add(usernameInfoLabel); 

JLabel versionInfoLabel = new JLabel("Version: " + GlobalValues.VERSION_NUMBER); 
Border versionInfoLabelBorder = versionInfoLabel.getBorder(); 
versionInfoLabel.setBorder(new CompoundBorder(versionInfoLabelBorder, infoLabelMargin)); 
infoBox.add(versionInfoLabel); 
+2

創建一個工廠類/方法,將創建這些'JLabel's具有相同屬性的? – Laf

+0

對於[示例](http://stackoverflow.com/a/10360374/230513)。 – trashgod

+0

這正是我所尋找的,thx – RHo

回答

0

代碼來創建標籤

infoBox.add(DefaultLayouts.infoLabel("Benutzer: " + GlobalValues.USERNAME)); 
infoBox.add(DefaultLayouts.infoLabel("Version: " + GlobalValues.VERSION_NUMBER)); 

類定義的默認標籤

public class DefaultLayouts { 
    public static JLabel infoLabel(String text) { 
     JLabel label = new JLabel(text); 

     Border margin = new EmptyBorder(10, 10, 10, 10); 
     Border border = label.getBorder(); 
     label.setBorder(new CompoundBorder(border, margin)); 

     return label; 
    } 
}