createImage problem

Hi,

I'm trying to create an Image of a swing component

and then display that Image. It seems that createImage

doesn't really create anything.

The following program demonstrates my problem:

import java.awt.*;

import javax.swing.*;

public class ImageViewer

{

JFrame i_mainFrame, jf2;

JButton i_button;

public ImageViewer()

{

i_button = new JButton("BIG BUTTON");

i_mainFrame = new JFrame("Main Frame");

i_mainFrame.getContentPane().add(i_button);

i_mainFrame.pack();

i_mainFrame.setVisible();

makeCopy();

}

public void makeCopy()

{

Image i = i_button.createImage(i_button.getSize().width, i_button.getSize().height);

jf2 = new JFrame("JF2");

jf2.getContentPane().paint(i.getGraphics());

jf2.pack();

jf2.setVisible(true);

}

public static void main(String[] args)

{

ImageViewer iv = new ImageViewer();

}

}

note that even if I change the line

Image i = i_button.createImage.....

to

Image i = i_mainFrame.createImage(i_mainFrame.getSize().width, i_mainFrame.getSize().height);

it doesn't work either.

I also can't use toolkit.createImage because the api

doesn't allow to create an image from a swing component.

Help would be greatly appreciated.

[1411 byte] By [clickd] at [2007-9-26 5:20:42]
# 1

The createImage() method of the Component class creates a blank Image object, which is typically used for double buffering.

Here is a method that creates a BufferedImage from a Swing component:

public static BufferedImage createImage(Component cmp) {

Rectangle d = cmp.getBounds();

BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bi.createGraphics();

//temporary container

JFrame jf = new JFrame();

jf.getContentPane().add(cmp);

jf.pack();

SwingUtilities.paintComponent(g2d,cmp,jf.getContentPane(), 0,0,d.width,d.height);

return bi;

}

Draw the image returned by this method over a graphics context in the paint() or paintComponent() method.

larryhr at 2007-6-29 19:26:12 > top of Java-index,Security,Cryptography...
# 2
it still draws a blank image and also the component whose image I am trying to draw..becomes blank suddenly.any clue?connie
connie04 at 2007-6-29 19:26:12 > top of Java-index,Security,Cryptography...