Wednesday, April 14, 2021

[Java Code Sample] How to use a custom font

 Here's the sample code to use a custom font in Java:

*Prepare ttf font and put it in your project folder



package p1;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;

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

public class Main {
	
	JFrame window;
	JPanel textPanel;
	JLabel textLabel;
	Font normalFont = new Font("Times New Roman", Font.PLAIN, 28);
	Font pixelMplus;

	public static void main(String[] args) {

		new Main();
	}
	
	public Main(){
		
		try{
            // load a custom font in your project folder
			pixelMplus = Font.createFont(Font.TRUETYPE_FONT, new File("yourFontName.ttf")).deriveFont(30f);	
			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("yourFontName.ttf")));			
		}
		catch(IOException | FontFormatException e){
			
		}
						
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		textPanel = new JPanel();
		textPanel.setBounds(100, 250, 600, 250);
		textPanel.setBackground(Color.black);
		
		textLabel = new JLabel("Hello traveler!");
		textLabel.setBackground(Color.black);
		textLabel.setForeground(Color.white);
		textLabel.setFont(pixelMplus);
		textPanel.add(textLabel);
		
		window.add(textPanel);
		
		window.setVisible(true);		
	}
}

Result:


(I used a font called "PixelMplus10-Regular")


Here's my video tutorial:



No comments:

Post a Comment