Search code examples
javaswingjtextfieldjava-7absolute-path

How to copy a file and paste the full path to a JTextField


Is it possible in Java to copy a file from the OS and paste it in a JTextField putting the full path of the copied file?

For example, i have the file "text.txt" on my desktop.

So i copy it with RightClick -> Copy

In the JFrame of my Java Application i focus into a JTextField and i use CTRL+V to paste.Then the application should paste the full path of copied file into the JTextField


Solution

  • You can use Java's Clipboard Class. Here is an Example

    Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
     List<File> filesList= (List<File>)sysClip.getData(DataFlavor.javaFileListFlavor);
              if(filesList!= null){
        Iterator<File> it = filesList.iterator();
        while(it.hasNext()){
            System.out.println(it.next().getAbsolutePath());
        }
    }