2016-03-30 40 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

applyFontChangeを設定し、 '私はJLabelの通常のway'をフォントサイズを変更する方法を知っている - そして、通常の方法を使用します。理由のためにその正常さ。他のアプローチを使用する理由はありません。あなたが持っているソリューションは、すべてのラベルが同じパネルにある場合にのみ機能します。まれに、単一のパネルと単一のレイアウトマネージャーを使用してGUIを作成します。解決方法は簡単です。 – camickr

+0

私は通常の方法を使用して、私はちょうどそれを行うには簡単な方法があったと見ていた。私はGUIの初心者ですが、かなり最近になって始めました。ありがとうございました – Aaronward

答えて

3

を変更したいものをJLabelsのための新しいクラスを作成し、それは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)); 
     } 
    } 
} 

もう一つの方法。ラベル作成に

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); 
     } 
    } 
} 

は、

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

事は、私は複数のラベルが悪いGridLayoutで使用している、例えば私はテキスト "名前でラベルを持っている:"それからラベルは、新しいJLabe(student.getName( )) '...だから私はすべての単一のJLabelのforループを書く必要はありません。 – Aaronward

+0

変更するラベルのメソッドを作成したり、新しいクラスを作成したりすることができます。私は私の答えを編集します。 – RubioRic

+1

@Aaronward更新された答え。 – RubioRic

関連する問題