1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class TextRenderingPane extends JComponent {
private BufferedImage offscreenImage;
private Paint textPaint = Color.RED;
private Font textFont = new Font("Dialog", Font.BOLD, 300);
private String text = "The crazy fox jumps over the lazy dog.";
public TextRenderingPane() {
addComponentListener(new ComponentAdapter() {
/**
* {@inheritDoc}
*/
@Override
public void componentResized(ComponentEvent evt) {
offscreenImage = null;
repaint();
}
});
}
/**
* {@inheritDoc}
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Insets insets = getInsets();
Dimension size = getSize();
int width = size.width - (insets.left + insets.right);
int height = size.height - (insets.top + insets.bottom);
if (width <= 0 || height <= 0) {
return;
}
if (offscreenImage == null) {
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
offscreenImage = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
Graphics2D g2d = offscreenImage.createGraphics();
try {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setPaint(textPaint);
g2d.setFont(textFont);
LineMetrics ln = textFont.getLineMetrics(text, g2d.getFontRenderContext());
g2d.drawString(text, 10, 10 + ln.getAscent());
} finally {
g2d.dispose();
}
}
Graphics2D g2d = (Graphics2D) g.create(insets.left, insets.top, width, height);
try {
g.drawImage(offscreenImage, 0, 0, null);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setPaint(textPaint);
g2d.setFont(textFont);
LineMetrics ln = textFont.getLineMetrics(text, g2d.getFontRenderContext());
g2d.drawString(text, 10, 2 * (10 + ln.getAscent()));
} finally {
g2d.dispose();
}
}
} |
Partager