7

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);

}

}
Community
  • 1
  • 1
ewok
  • 20,148
  • 51
  • 149
  • 254

2 Answers2

5

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.

unholysampler
  • 17,141
  • 7
  • 47
  • 64
  • Thanks! that fixed it. Will I still be able to alter the properties of the text field (change the text inside, for instance) if it is declared final? – ewok Mar 12 '12 at 15:37
  • 1
    @ewok: Yes. The only thing `final` does to a variable is ensure that you do not assign another value/reference to it after it is initialized. – unholysampler Mar 12 '12 at 15:58
0

Another option is to declare the variable static.


    static JTextArea myPanel = new JTextArea();

no one
  • 1