I need to create an image from a JPanel, that has not been displayed
on the screen. I.e. I recieve a JPanel and want to pass it as image to
a library without showing the JPanel to the user.
My idea is to do something like this:
public void doSomething(JPanel originalPanel) {
testImage(getImage(originalPanel));
}
public Image getImage(JPanel aPanel) {
Image image = aPanel.createImage(aPanel.getWidth(),
aPanel.getHeight());
return image;
}
public void testImage(Image aImage) {
JFrame frame = new JFrame("testImage");
JLabel label = new JLabel(new ImageIcon(aImage));
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
But this gives a:
java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
because the Image returned by getImage() is null.
Has anybody some suggestions how to get an image object from a panel
that hasn't been displayed?
Thx
Norbert
The behavior is in line with the documented behavior. So in short, you
can't. Create a separate BufferedImage and use that one.
/Thomas
--
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
Probably because the Panel hasn't been validated. Since the panel hasn't
been added to anything, you will have to set its bounds manually and
also call validate on it so that it will perform a layout of its child
components. (In case the panel has child components, you need to
experiment a bit to see if the validate call really works - There are a
lot of places where AWT code will avoid performing validations if the
component is not visible)
BK