Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change JLabel Font size [duplicate]

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);
     }
like image 359
fayez abd-alrzaq deab Avatar asked Jul 26 '13 15:07

fayez abd-alrzaq deab


2 Answers

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);
like image 162
Laf Avatar answered Nov 09 '22 07:11

Laf


Don't confuse the deriveFont method which expects a style argument over the one that expects a font size. The one that you're using uses the style argument and has no bearing on the actual font size. Instead use

intro.setFont(intro.getFont().deriveFont(64f)); 

Also don't add components in the paint method. Your currrent application will not display the JLabel until a repaint is done. Overriding paint (or more correctly paintComponent for Swing) is intended for custom painting but the adding components does not qualify as such. The application will have the overhead of the component being added every time a repaint is done.

Example:

enter image description here

public class LabelDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Label Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                JLabel intro = new JLabel("משחק זיכרון");
                frame.add(intro);
                intro.setFont(intro.getFont().deriveFont(64f));
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
like image 37
Reimeus Avatar answered Nov 09 '22 08:11

Reimeus