Use Font in Java Swing Application

In the Java Swing application, we can use different fonts for displaying text in graphical user interface components like labels, buttons, text fields, and so on. Following is an example code snippet that demonstrates how to use the font in the Java Swing application.

Let’s see a font used for a JLabel component in the following example:

import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class FontDemo extends JFrame {
	public FontDemo() {
		super("Font Demo");
		JLabel label = new JLabel("Hello, world!");
		Font font = new Font("Serif", Font.BOLD, 24); // create a font object
		label.setFont(font); // set the font for the label
		add(label);
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	public static void main(String[] args) {
		new FontDemo();
	}

}

In the above code, we create a new font object using the Font class constructor. The first parameter is the name of the font family, the second parameter is the style (bold, italic, plain, etc.), and the third parameter is the font size. We then set the font for the label component using the setFont() method.

The output of the above code is:

Use Font in Java Swing Application Font Demo

Use custom font

We can use any font family that is installed on our system, or we can load a custom font file using the Font.createFont() method. Following is an example that loads a custom font file and sets it for a JLabel:

import java.awt.Font;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class CustomFontDemo extends JFrame {
	public CustomFontDemo() {
		super("CustomFont Demo");
		JLabel label = new JLabel("Hello, world!");
		try {
			Font font = Font.createFont(Font.TRUETYPE_FONT,
					new File("C:\\Users\\codersathi\\Downloads\\roboto\\Roboto-BoldItalic.ttf")); // load custom font
			font = font.deriveFont(Font.BOLD, 24); // set font style and size
			label.setFont(font); // set the font for the label
		} catch (Exception e) {
			e.printStackTrace();
		}
		add(label);
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	public static void main(String[] args) {
		new CustomFontDemo();
	}

}

In this example, I first load a custom font file using the Font.createFont() method. The first parameter is the font type (TrueType or OpenType), and the second parameter is the font file that I’ve downloaded the font called Roboto (Make sure to UnZip it before using). I then set the font style and size using the deriveFont() method, and finally, we set the font for the label component using the setFont() method.

The output of this font looks like:

Use Font in Java Swing Application Roboto font


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments