2016-03-30 54 views
0

我知道如何改變一個JLabel的字體大小正常方式如何更改「panel.add(new JLabel(」「))中的JLabel的字體大小;」

exampleLabel.setFont(new Font("", Font.PLAIN, 20)); 

但是我想看看是否有這樣做,當你添加一個JLabel到面板簡單的方法的一種方式。像這樣..

examplePanel.add(new JLabel("this is an example")); 

我將如何更改後者的字體大小,因爲JLabel沒有名稱?

我試圖在JPanel上設置字體,但它不起作用。

examplePanel.setFont(.......); 

任何幫助,這將不勝感激。

+1

'我知道如何改變一個JLabel的字體大小正常way' - 然後用正常的方式。它的正常是有原因的。沒有理由使用其他方法。如果所有標籤都位於同一面板上,則只有該解決方案纔有效。很少會創建一個具有單個面板和單個佈局管理器的GUI。保持解決方案簡單。 – camickr

+0

我採取了正常的方式,我只是看到是否有一個更簡單的方法來做到這一點。我是GUI的新手,最近纔剛剛開始。感謝您的建議 – Aaronward

回答

3

這是訪問一個JLabel一種奇怪的方式,但是這可能工作...

Component[] components = examplePanel.getComponents(); 

for (Component singleComponent : components) { 
    if (singleComponent instanceof JLabel) { 
     JLabel label = (JLabel) singleComponent; 

     if ("this is an example".equals(label.getText()) { 
       label.setFont(new Font("", Font.PLAIN, 20)); 
     } 
    } 
} 

的另一種方式,請爲你想改變那些JLabels一個新的類。

public class JMyFontLabel extends JLabel { 
    boolean applyFontChange = false; 

    public JMyFontLabel(String text, boolean applyFontChange) { 
     super(text); 
     this.applyFontChange = applyFontChange; 
    } 

    // get/set methods for applyFontChange. 
} 

// Method to apply font 
public void setMyFont(JPanel examplePanel, Font myFont) { 
    Component[] components = examplePanel.getComponents(); 

    for (Component singleComponent : components) { 

    if (singleComponent instanceof JMyFontLabel) { 
     JMyFontLabel label = (JMyFontLabel) singleComponent; 

     if (label.isApplyFontChange()) { 
      label.setFont(myFont); 
     } 
    } 
} 

在創建標籤,設置applyFontChange

examplePanel.add(new JMyFontLabel("Name", true)); 
+0

事情是,我有多個標籤,不適合在GridLayout中使用,例如我有一個帶有文本「Name:」的標籤,那麼它旁邊的標籤將是'new JLabe(student.getName ))'...所以我不想爲每個JLabel寫一個for循環。 – Aaronward

+0

您可以爲要更改的標籤編寫方法或創建新類。我會編輯我的答案。 – RubioRic

+1

@Aaronward更新回答。 – RubioRic