Drag the Java Swing JTextField file path

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) { /* * 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); } } 
+6
source share
2 answers

As the error message myPanel , myPanel must be defined as final.

 final JTextArea myPanel = new JTextArea(); 

In this way, the inner class can be assigned one reference pointer to an instance of the variable without worrying that the variable can be changed to point to something even later at runtime.

+5
source

Another option is to declare a static variable.

     static JTextArea myPanel = new JTextArea ();

0
source

Source: https://habr.com/ru/post/910516/


All Articles