4

I want to print some text using the paintComponent(..) method.

@Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.red);
    g.drawString("Hello world", 10, 10);
}

But the text is somewhat jaggy. How could you force text drawing with [anti-aliasing] in this method?

Thank you.

Benjamin R
  • 555
  • 6
  • 25
Sanjeev
  • 397
  • 1
  • 8
  • 20

1 Answers1

9

You can set double buffering by:

class MyPanel extends JPanel {
    public MyPanel() {
        super(true);//set Double buffering for JPanel
    }
}

or simply call JComponent#setDoubleBuffered(..).

You can also set RenderingHints for Graphics2D objects like anti-aliasing and text anti-aliasing to improve Swing painting quality by:

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g); 
    Graphics2D graphics2D = (Graphics2D) g;

    //Set  anti-alias!
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON); 

   // Set anti-alias for text
    graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 

    graphics2D.setColor(Color.red);
    graphics2D.drawString("Hello world", 10, 10);
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • I think you should remove the double buffering part from the answer to avoid confusion. For that, there are [other questions](https://stackoverflow.com/questions/4430356/java-how-to-do-double-buffering-in-swing). – user202729 Jul 19 '18 at 08:48
  • Is it enough to set this in the constructor of the JPanel or do I have to set this strategy in every call to paintComponent? – hreinn Oct 30 '20 at 21:43