Question

I have a JPanel which draws .png images. each image has 2 copies to signify whether or not it has been selected. One image is normal and one has a colored border to signify the selection has been made. (You can think of these images as simple shapes for the sake of argument)

Which version of the image is drawn is determined via MouseListeners. If the user selects image1, then image1 will display its highlighted version.

In general this is working, however upon repaint() the highlighted version of the image is left behind. Since the highlighted version is slightly larger than the normal version, you can see it sticking out behind the newly drawn normal image (overlapping).

I thought repaint() was supposed to completely dispose of the current drawings and start from scratch, this doesn't seem to be the case here. Below is the general idea, blackClicked is toggled inside a MouseListener.

So my question is how do I make repaint() get rid of its currently drawn images and start from scratch.

Also, if there is a simpler way to achieve all of this please let me know, making 2 copies of images is tedious work.

@Override
public void paintComponent(Graphics g){

    Graphics2D g2 = (Graphics2D) g;

    if(blackClicked)
        g2.drawImage(blackSelected,0, 0, null);
    else
        g2.drawImage(black,0, 0, null);

    g2.drawImage(green,0, 0, null);
}
Was it helpful?

Solution

how do I make repaint() get rid of its currently drawn images and start from scratch.

You mean, how to make repaint fill the component with it's background color before painting? How about adding

g2.setColor(getBackground());
g2.fillRect(0, 0, getWidth(), getHeight());

in top of paintComponent()?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top