Search code examples
javaswinguser-interfacejlabel

How to change the font size of a JLabel that is in a "panel.add(new JLabel(""));"


I know how to change the font size of a JLabel the normal way

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

But im looking to see if there is a way of doing it when you add a JLabel to a panel the simple way. like this..

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

How would i change the font size of the latter, seeing as the JLabel doesn't have a name?

i tried setting the font on the JPanel but it doesn't work.

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

Any help with this would be appreciated.


Solution

  • It's a strange way to access a JLabel but this may work ...

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

    Another way, create a new class for those JLabels that you want to change.

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

    On label creation, set applyFontChange

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