Java – Drag and Drop file path to Java Swing JTextField

drag-and-dropjavaswing

Using this question, I created the class below, which handles drag and drop of files to a JTextField. The point of the application is to be able to drag a file into the text field, and have the text field's text set to the file's path (you can see the goal in the code pretty clearly).

My problem is the below code does not compile. The compilation error states Cannot refer to non-final variable myPanel inside an inner class defined in a different method. I haven't worked much with inner classes, so can seomeone show me how to resolve the error and get the code to behave as designed?

Code:

import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.util.List;

import javax.swing.*;

public class Test {

public static void main(String[] args) {
    JTextArea myPanel = new JTextArea();

    myPanel.setDropTarget(new DropTarget() {
        public synchronized void drop(DropTargetDropEvent evt) {
            try {
                evt.acceptDrop(DnDConstants.ACTION_COPY);
                List<File> droppedFiles = (List<File>) evt
                        .getTransferable().getTransferData(
                                DataFlavor.javaFileListFlavor);
                for (File file : droppedFiles) {
                    /*
                     * NOTE:
                     *  When I change this to a println,
                     *  it prints the correct path
                     */
                    myPanel.setText(file.getAbsolutePath());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });

    JFrame frame = new JFrame();
    frame.add(myPanel);
    frame.setVisible(true);

}

}

Best Solution

As the error message says, myPanel needs to be defined as final.

final JTextArea myPanel = new JTextArea();

This way the inner class can be given one reference pointer to the variable instance without concern that the variable might be changed to point to something else later during execution.