问题
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.
回答1:
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 RenderingHint
s 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);
}
来源:https://stackoverflow.com/questions/13236797/anti-aliasing-in-paintcomponent-method