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

how to clear the image from jpanel

897 views
Skip to first unread message

jimgardener

unread,
Oct 28, 2010, 9:30:13 AM10/28/10
to
I have an ImagePanel subclassed from JPanel ,where I can set an image

class ImagePanel extends JPanel{
private BufferedImage bi;
public ImagePanel(){
super();
}
public void setImage(String imagefilename) throws IOException{
bi = ImageIO.read(new File(imagefilename));
this.setPreferredSize(new Dimension(bi.getWidth(),bi.getHeight()));

this.revalidate();
this.repaint();
}
@Override
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
g.drawImage(bi,0,0,null);
}
}

I can set the image by giving an image filename.But I wish to clear
the previous image from the panel,thus showing a blank image panel,if
a user supplies an invalid image name.
How can I do this?Can someone please tell me?
thanks

jim

Knute Johnson

unread,
Oct 28, 2010, 12:07:33 PM10/28/10
to

If no image gets loaded, set the reference to null and test for that in
the paintComponent() method and don't draw the image just clear the
background.

--

Knute Johnson
email s/nospam/knute2010/

John B. Matthews

unread,
Oct 28, 2010, 2:50:45 PM10/28/10
to
In article <ddhyo.3138$lM....@newsfe23.iad>,
Knute Johnson <nos...@rabbitbrush.frazmtn.com> wrote:

> On 10/28/2010 6:30 AM, jimgardener wrote:
> > I have an ImagePanel subclassed from JPanel ,where I can set an image
> >
> > class ImagePanel extends JPanel{
> > private BufferedImage bi;
> > public ImagePanel(){
> > super();
> > }
> > public void setImage(String imagefilename) throws IOException{
> > bi = ImageIO.read(new File(imagefilename));
> > this.setPreferredSize(new Dimension(bi.getWidth(),bi.getHeight()));
> >
> > this.revalidate();
> > this.repaint();
> > }
> > @Override
> > public void paintComponent(Graphics g) {
> > g.setColor(getBackground());
> > g.fillRect(0,0,getWidth(),getHeight());
> > g.drawImage(bi,0,0,null);
> > }
> > }
> >
> > I can set the image by giving an image filename.But I wish to clear
> > the previous image from the panel,thus showing a blank image
> > panel,if a user supplies an invalid image name. How can I do
> > this?Can someone please tell me?

> [...]


>
> If no image gets loaded, set the reference to null and test for that
> in the paintComponent() method and don't draw the image just clear
> the background.

Knute's right; and if you forget the test, as I have sometimes done, the
drawImage() method "does nothing if img is null."

<http://download.oracle.com/javase/6/docs/api/java/awt/Graphics.html>

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

Knute Johnson

unread,
Oct 28, 2010, 5:45:21 PM10/28/10
to

I never noticed that before. I must have been trying to protect against
a NullPointerException that never gets thrown.

0 new messages