Change JLabel Font size

fayez abd-alrzaq deab picture fayez abd-alrzaq deab · Jul 26, 2013 · Viewed 61.4k times · Source

I was trying to change the font size of JLabel, I tried to set Font but it is always the same!

Here is some of the code:

 @Override
 public void paint(Graphics g) {
 super.paint(g);
 Container cont=this.getContentPane();
 intro=new JLabel("משחק זיכרון");
 intro.setForeground(Color.YELLOW);
 intro.setFont(intro.getFont().deriveFont(64.0f));
 intro.setHorizontalAlignment( SwingConstants.CENTER );
 cont.add(intro);
     }

Answer

Laf picture Laf · Jul 26, 2013

You are calling the wrong deriveFont method.

The parameter in deriveFont(int) is the style (bold, italic, etc.). The method you are looking for is deriveFont(float).

In your case, the only change you need to make is intro.setFont(intro.getFont().deriveFont(64.0f));.

Here's a short code example that does display a label with font size 64:

JFrame frame = new JFrame ("Test");
JLabel label = new JLabel ("Font Test");
label.setFont (label.getFont ().deriveFont (64.0f));
frame.getContentPane ().add (label);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.pack ();
frame.setVisible (true);