DEV Community

sadiul hakim
sadiul hakim

Posted on

How to use custom font in java swing....

Hello there, I am back again.

Today i am going to show you how you can use custom font or how you can customize your fonts in java swing.So, Let's get started...

First we need to create a Frame..

import javax.swing.JFrame;

public class CustomFont extends JFrame{

    public CustomFont()  {
        this.setBounds(300,100,400,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        CustomFont frame=new CustomFont();
        frame.setVisible(true);
    }
}

Enter fullscreen mode Exit fullscreen mode


java
This will create a nice frame.

I do not want to use any Layout for that i need to add this line in the Constructor

this.setLayout(null);
Enter fullscreen mode Exit fullscreen mode

Now i want to use custom font in a textField.For that i need to create a field.

First import JTextField

import javax.swing.JTextField;
Enter fullscreen mode Exit fullscreen mode

Declare textField as a private class field

private JTextField text;
Enter fullscreen mode Exit fullscreen mode

Now create and add textField to the frame

text=new JTextField();
text.setBounds(20,20,150,30);
add(text);
Enter fullscreen mode Exit fullscreen mode

Now i want to customize this fields font
For that i need to create an instance of Font class.You can create an instance of font class like this.

First import Font class

import java.awt.Font;
Enter fullscreen mode Exit fullscreen mode

Then

Font font=new Font("Fira Code",Font.PLAIN,12);
Enter fullscreen mode Exit fullscreen mode

First you need to give Font Name then Font Style and Font size.Now you need to add the font to the field.

 text.setFont(font);
Enter fullscreen mode Exit fullscreen mode

Now your field should have a customized font.

Top comments (0)