javafx实现拖人文件到node,将node里面的内容为文件保存

最近研究了下javafx客户端人性化方面的,拖来拖去什么的最爱了,接下来给大家讲解下javafx怎么获取拖入的文件和将node里面的内容拖出为文件

1.获取拖入的文件

        
        //build drag
        txtAreaChangePane.setOnDragOver(new EventHandler<DragEvent>() { //node添加拖入文件事件
            public void handle(DragEvent event) {
                Dragboard dragboard = event.getDragboard(); 
                if (dragboard.hasFiles()) {
                    File file = dragboard.getFiles().get(0);
                    if (file.getAbsolutePath().endsWith(".java")) { //用来过滤拖入类型
                        event.acceptTransferModes(TransferMode.COPY);//接受拖入文件
                    }
                }

            }
        });
        txtAreaChangePane.setOnDragDropped(new EventHandler<DragEvent>() { //拖入后松开鼠标触发的事件
            public void handle(DragEvent event) {
                // get drag enter file
                Dragboard dragboard = event.getDragboard();
                if (event.isAccepted()) {
                    File file = dragboard.getFiles().get(0); //获取拖入的文件
                    
                }
            }
        });

2.拖出生成文件

//drag out 
          ClipboardContent content = new ClipboardContent(); //用来放拖出的内容
        txtAreaCodeSpace.setOnDragDetected(new EventHandler<MouseEvent>() { //在node里面拖动事件
            public void handle(MouseEvent event) {
                
                    Dragboard dragboard = txtAreaCodeSpace.startDragAndDrop(TransferMode.ANY); //开启拖出事件
                    content.clear();
                    File file = new File(txtClassName.getText() + ".java"); //创建拖出的文件
                    OutputStreamWriter outputString = null;
                    try {
                        file.createNewFile();
                        outputString = new OutputStreamWriter(new FileOutputStream(file));
                        outputString.write(txtAreaCodeSpace.getText());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            outputString.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        outputString = null;
                    }
                    List<File> files = new ArrayList<File>();
                    files.add(file);
                    content.putFiles(files); //将文件保存到面板里面
                    dragboard.setContent(content); //放入拖出内容
                
            }
        });

就是这么简单,javafx封装的还是挺多的。

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0