Re: paintComponent into a BuffereImage?
Thomas Fritsch wrote:
fiziwig" <fiziwig@yahoo.com> wrote:
It seems like I should be able to override the paintComponent method of
a class and have it do its paint into a BufferedImage something like
this:
public void paintComponent(Graphics g) {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = image.createGraphics();
super.paintComponent( g2D );
.. etc ...
Be aware that paintComponent() may be called hundreds of times per second,
depending on what you do with your GUI (moving it, maximizing it, resizing
it, ...). It is therefore not a good idea to create a new BufferedImage each
time, and paint on it.
FWIW: I solved the problem like this:
class TextPanel extends JTextPane {
// implements rotation for a JTextPane
private int rotation;
private int tx, ty;
private int wide, high;
private BufferedImage renderedText = null;
// valid rotation values are:
// 0 = no rotation
// 1 = rotation 90 degree clockwise
// 2 = rotation 180 degrees
// 3 = rotation 90 degrees counterclockwise
TextPanel() {
super();
rotation = 0;
tx = 0;
ty = 0;
}
public void setDefaultBounds( int x, int y, int width, int height)
{
high = height;
wide = width;
super.setBounds(x,y,width,height);
}
public void setRotation( int newRotation ) {
newRotation = newRotation % 4;
if ( rotation != newRotation ) {
switch (newRotation) {
case 0 : tx = 0; ty = 0; break;
case 1 : tx = 1; ty = 0; break;
case 2 : tx = 1; ty = 1; break;
case 3 : tx = 0; ty = 1; break;
}
if ( newRotation != 0 ) {
if ( renderedText==null) {
rotation = 0; // so that text is actually rendered
renderedText = new BufferedImage(wide, high,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = renderedText.createGraphics();
paint( g2D );
}
}
rotation = newRotation; // so the repaint will paint the
rendered image
if ((rotation%2)==0) {
setSize(wide,high);
} else {
setSize(high,wide);
}
repaint();
}
}
public int getRotation() { return rotation; }
public void paintComponent(Graphics g) {
if ( rotation == 0 ) {
super.paintComponent(g);
return;
}
Graphics2D g2 = (Graphics2D) g;
double angle = rotation * Math.PI/2;
AffineTransform tr = g2.getTransform();
if (rotation==2) {
tr.setToTranslation(wide*tx,high*ty);
} else {
tr.setToTranslation(high*tx,wide*ty);
}
tr.rotate(angle);
g2.drawImage(renderedText, tr, this);
}
}
--gary