Java – Drag and Drop file path to Java Swing JTextField


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?


import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
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 {
                List<File> droppedFiles = (List<File>) evt
                for (File file : droppedFiles) {
                     * NOTE:
                     *  When I change this to a println,
                     *  it prints the correct path
            } catch (Exception ex) {

    JFrame frame = new JFrame();



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.