如何更改 "panel.add(new JLabel("") 中的 JLabel 的字体大小);"

How to change the font size of a JLabel that is in a "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(.......);

如有任何帮助,我们将不胜感激。

这是一种访问 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 创建一个新的 class。

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