0

I make a ImagePanel class that get a ImageIcon object and draw it show panel.

import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.awt.Graphics;

class ImagePanel extends JPanel {
    private ImageIcon img;

    public ImagePanel(ImageIcon img) {
        this.setImage(img);
    }

    public void setImage(ImageIcon img){
        this.img = img;

    }

    @Override
    public void paintComponent(Graphics g) {
        if(img instanceof ImageIcon)
            g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
    }
}

but the problem is when I change the img, it don't show it on panel till I change frame size. how can I update it?

EDIT: repaint() does not clean last img on panel.

  • 1) For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Feb 06 '14 at 11:29

1 Answers1

3

Typically you would simply need to call repaint within the setImage method.

You should be calling super.paintComponent in order to prevent any possibility of introducing paint artifacts into your rendering process.

You should should consider overriding getPreferredSize in order to ensure that the component will be laid out properly under most layout managers. This should reflect the size of the img.

Unless you have some reason to do otherwise, you could just get away with using JLabel

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I cant use JLabel because I need add some object to it and I need image size be some az Panel size. and I have use repaint() before but it don't delete last img. – Arman Mazdaee Feb 06 '14 at 11:07
  • *"You should be calling `super.paintComponent` in order to prevent any possibility of introducing paint artifacts into your rendering process."* +1. From the sounds of it, that is the exact cause of this problem. – Andrew Thompson Feb 06 '14 at 11:30
  • _I don't get it. where should I add super.paintComponent() and what parameter should I use for It?_ You can override a method but don't know how to call its super? Time for going back to the introductory chapters of a decent tutorial on java :-) – kleopatra Feb 06 '14 at 12:27