2

I have a JPanel configured as a dropzone that lets the user drop files in it in order to be analyzed. Now I want to change the background color of that panel when the file is being dragged over it.

How can this be done?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • The question is too broad start by checking https://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html, when you have implemented the drag and drop features, it will be fairly easy to also change the background of the JPanel (.setBackground) – Petter Friberg Jul 13 '17 at 22:22
  • 1
    [That's one way you could do it](https://stackoverflow.com/questions/13597233/how-to-drag-and-drop-files-from-a-directory-in-java/13597635#13597635) - You could get the same affect by simply setting the background color to the desired color, but this allows for alpha based colors – MadProgrammer Jul 13 '17 at 22:23

1 Answers1

3

One way is to add a DropTarget. Something like this:

yourJpanel.setDropTarget(new DropTarget() {

    @Override
    public synchronized void drop(DropTargetDropEvent dtde)
    {
        this.changeToNormal();
        //handle the drop ....
    }

    @Override
    public synchronized void dragEnter(DropTargetDragEvent dtde){

        //Change JPANEL background...
        yourJpanel.setBackground(Color.RED);
    }

    @Override
        public synchronized void dragExit(DropTargetEvent dtde) {
        this.changeToNormal();
    }

    private void changeToNormal() {   
        //Set background to normal...
        yourJpanel.setBackground(Color.WHITE);
    }
});
Akila
  • 1,258
  • 2
  • 16
  • 25