Using this question , I created a class below that handles dragging and dropping files into a JTextField. The application point should be able to drag the file into the text field and have the text of the text field set to the file path (you can clearly see the target in the code).
My problem is that the code below does not compile. Compilation error Cannot refer to non-final variable myPanel inside an inner class defined in a different method
. I did not work much with inner classes, so can I show you how to resolve the error and make the code behave the way it was designed?
the 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) { myPanel.setText(file.getAbsolutePath()); } } catch (Exception ex) { ex.printStackTrace(); } } }); JFrame frame = new JFrame(); frame.add(myPanel); frame.setVisible(true); } }
source share