user1110343
user1110343

Reputation: 11

Java Swing Repaint an image

I'd like to implement a DragAndDrop for an Image but can't seem to get the Swing repaint function to work on the specific Image.

Code:

public class playerFrame extends JFrame{
...
    private void destroyerImageMouseDragged(java.awt.event.MouseEvent evt)  
    }                                             
    repaintCurrentPosition(evt);
    }               

    public void repaintCurrentPosition(MouseEvent e){
        this.setLocation(e.getX(), e.getY());
        this.repaint();
    }

this.repaint <- this function repaints the whole frame and not just the Image I'd like it to repaint, which is about 50x50 size. How do you repaint a specific JPEG image without creating a new class?

thanks.

Upvotes: 1

Views: 6477

Answers (4)

camickr
camickr

Reputation: 324207

How are you doing the drag and drop?

The easiest way is to just add an Icon to a JLabel and then drag the label around. Everytime you invoke setLocation(...) on the label it will repaint() itself.

The Component Mover class does all the hard work for you.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109823

not just the Image I'd like it to repaint, which is about 50x50 size

JComponent#paintImmediately carefully with EDT

Upvotes: 1

GETah
GETah

Reputation: 21459

this.repaint will force the parent frame to be repainted. Call repaint only on the control holding your image.

Example: to refresh this image loaded onto the JLabel:

ImageIcon icon = createImageIcon("images/middle.gif");
label = new JLabel("Image and Text", icon, JLabel.CENTER);

You do:

label.repaint();

Upvotes: 1

Petar Minchev
Petar Minchev

Reputation: 47403

Call repaint only on the panel where your image is drawn.

Upvotes: 0

Related Questions