Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Getting an image object from a JPanel that is not visible

0 views
Skip to first unread message

Norbert

unread,
Nov 26, 2004, 6:54:58 AM11/26/04
to
Hi Newsgroup!

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

Thomas Weidenfeller

unread,
Nov 26, 2004, 7:20:00 AM11/26/04
to
Norbert wrote:
> 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?

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

Babu Kalakrishnan

unread,
Nov 29, 2004, 2:39:07 AM11/29/04
to
Norbert wrote:
> Thomas Weidenfeller <nob...@ericsson.invalid> wrote in message news:<co76qh$2sr$1...@newstree.wise.edt.ericsson.se>...

>
>>Norbert wrote:
>>
>>>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?
>>
>>The behavior is in line with the documented behavior. So in short, you
>>can't. Create a separate BufferedImage and use that one.
>>
>>/Thomas
>
> Hi,
>
> I think you are talking of something like this:
>
> public Image getImage(JPanel aPanel) {
> BufferedImage image = new BufferedImage(500, 500,
> BufferedImage.TYPE_INT_RGB);
> Graphics2D g2d = image.createGraphics();
> aPanel.paint(g2d);
> return image;
> }
>
> But this gives me only a black image. Any further suggestions or do I
> make a misstake?
>

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

0 new messages