Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my JLabel's text, using a custom font, antialiased?

I'm trying to create a SWING application using Java 1.6 and I have a JLabel that uses a custom font from a .ttf file.

I thought 1.6 had anti-aliasing on by default, but my text is pretty pixelized.

Here's a code sample and an image showing the result:

package aceprobowler.test;

import java.awt.Color;
import java.awt.Font;
import java.io.InputStream;

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

import aceprobowler.options.OptionsValues;

public class TestAntialiasedText extends JFrame
{
    private static final long serialVersionUID = 2411330284507353990L;

    public TestAntialiasedText(String title)
    {
        super(title);
        setSize(800,200);
        
        Font titleFont = null;
        
        try
        {
            InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
            titleFont = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.PLAIN, 60);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            System.err.println("font not loaded.  Using serif font.");
            titleFont = new Font("serif", Font.PLAIN, 24);
        }
        
        JPanel panelWithText = new JPanel();
        JLabel labelWithText = new JLabel("This is a test");
        
        labelWithText.setFont(titleFont);
        
        labelWithText.setBackground(Color.BLACK);
        labelWithText.setForeground(Color.WHITE);
        labelWithText.setOpaque(true);
        
        panelWithText.add(labelWithText);
        add(panelWithText);
    }
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new TestAntialiasedText("Testing text anti-alias").setVisible(true);
            }
        });
    }
}

Mostly apparent on the "T"s and on the "A" Not anti-aliased text

I tried creating an inner class overriding paintComponent(Graphics g) and using

Graphics2D g2 = (Graphics2D)g; 
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)

But it doesn't work. Can anyone help me out with this? I can't find any information on the internet about this since Javaj 1.6 is supposed to make everything SWING related Anti-aliased by default.

Thanks in advance!

like image 672
Adam Smith Avatar asked Jan 19 '23 21:01

Adam Smith


1 Answers

When you override the paintComponent method of the JLabel instance, I believe that you'll need to use the following:

  • Graphics.drawString(String str, int x, int y)
  • RenderingHints.KEY_TEXT_ANTIALIASING

For an example, see:

  • RichJLabel
like image 140
mre Avatar answered Jan 29 '23 22:01

mre