Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anti-aliasing in paintComponent() method

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.

like image 467
Sanjeev Avatar asked Jan 16 '23 03:01

Sanjeev


1 Answers

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);
}
like image 199
David Kroukamp Avatar answered Jan 17 '23 17:01

David Kroukamp