Having A Problem In Changing Font in java

1.3k Views Asked by At

I want to put a custom font using drawString method in my applet the problem is that it doesn't change the font even I do it properly. I am still student so please bare at me for my code. Please help me to change the font. I found out that there are certain fonts that java allowed to use in method font please help me.

import javax.swing.*;
import java.awt.*;
public class WoodyWoodPeckerShow extends JApplet {
    private Font font;



    public void init(){
        setFont(new Font("WoodPecker",Font.TRUETYPE_FONT,30));
    }

    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D)g;

        g2.setFont(font);
        g2.drawString("WoodyWoodPecker",10,200);


    }
}

It gives me the default font instead of like this enter image description here

Please help me. Thank you guys. Hope you can help me :)

2

There are 2 best solutions below

0
radulfr On

The instance variable font in your WoodyWoodPeckerShow class is null, because you only set the value of the superclass variable that has the same name. You can remove the instance variable altogether and use the one in the superclass, like this:

import javax.swing.*;
import java.awt.*;

public class WoodyWoodPeckerShow extends JApplet {
    @Override
    public void init() {
        setFont(new Font("WoodPecker", Font.TRUETYPE_FONT, 30));
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setFont(getFont());
        g2.drawString("WoodyWoodPecker", 10, 200);
    }
}
4
Gipsy King On

You haven’t set any properties for your font you declared, that’s why you got font with default size and style.

 g2.setFont(font);

You have to set all this stuff or declare new font as anonymous class , like:

g2.setFont(new Font("Some", Font.BOLD, 16));