1

I'm writing a custom JComponent and it will draw some text from a string.

Currently the text drawing code looks like this:

@Override
public void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);
    Rectangle bounds = graphics.getClipBounds();
    int maxAscent = graphics.getFontMetrics().getMaxAscent();
    graphics.setColor(Color.BLACK);
    graphics.drawString(text,bounds.x,bounds.y+maxAscent);
}

However, this draws aliased text. So I googled drawing antialiased text and found I could add these lines:

graphics2D.setRenderingHint(
    RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

But then I thought... what else am I missing? And what if the user disables antialiased text and the current look and feel honors this but my code does not.

I want to draw the text as the current look and feel would draw the text. How can I do that?

Jason
  • 11,709
  • 9
  • 66
  • 82

1 Answers1

0

You can use the desktop settings. It is explained here: http://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/DesktopProperties.html#awt.font.desktophints

Instead of using

graphics2D.setRenderingHint(
    RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

use

Toolkit tk = Toolkit.getDefaultToolkit();
Map map = (Map)(tk.getDesktopProperty("awt.font.desktophints"));
if (map != null) {
    graphics2D.addRenderingHints(map);
}
uoyilmaz
  • 3,035
  • 14
  • 25
  • http://stackoverflow.com/questions/8156772/drawing-text-in-java-look-and-feel-problems and http://stackoverflow.com/questions/8113708/how-to-set-text-above-and-below-a-jbutton-icon/8115820 suggest that this is not a cross platform approach (i.e., it will not work in all situations). – Jason Aug 21 '15 at 15:57