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"
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!
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
I believe that the default for font anti-aliasing varies by platform. You don't say what platform you are on. In any case, setting the text antialiasing rendering hint should fix it.
Another approach is to use TextLayout
and supply a FontRenderContext
that isAntiAliased
, as shown here.
精彩评论