将文件路径拖放到Java Swing JTextField [英] Drag and Drop file path to Java Swing JTextField

查看:224
本文介绍了将文件路径拖放到Java Swing JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此问题,我创建了下面的类,可以将文件拖放到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).

我的问题是下面的代码不能编译。编译错误说明不能在不同的方法中定义的内部类中引用非最终变量myPanel。我没有与内部课程很多,所以可以seomeone告诉我如何解决错误,并得到代码的行为设计?

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

}

}


推荐答案

如错误消息所示, myPanel 需要定义为final。

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.

这篇关于将文件路径拖放到Java Swing JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆