Arman Mazdaee
Arman Mazdaee

Reputation: 25

call paintComponet agian

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.

Upvotes: 0

Views: 51

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

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

Upvotes: 3

Related Questions