javafx框架tornadofx入门实战20_dragAndDrop-chooseFile-chooseDirecory

2020-03-19 14:41:45 浏览数 (1)

本实战演示打开或拖拽文件或目录到文本框中,将文件或目录路径或内容显示在文本框中

代码语言:javascript复制
import javafx.scene.input.TransferMode
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File

class APP21 : App(MainView21::class)
class MainView21 : View("tornadofx入门20_dragAndDrop-chooseFile-chooseDirecory") {
    val content = stringProperty()
    override val root = borderpane {

        center = vbox(5) {
            textarea(content) {
                isWrapText = true
                setOnDragOver {
                  if (it.gestureSource != this && it.dragboard.hasFiles()) {
                      //这一句必须有,否则setOnDragDropped不会触发
                      it.acceptTransferModes(*TransferMode.COPY_OR_MOVE)
                  }
                  it.consume()
                }

                setOnDragDropped {
                  if (it.dragboard.hasFiles()) {
                      val file = it.dragboard.files.first()
                      content.value=file.readText()
                      it.isDropCompleted = true
                  }

                  it.consume()
                }
            }
        }
        top = hbox(5) {
            label("choose or drag file to the textarea below")
        }
        left = vbox(10) {
            button("save") {
                action {
                    _chooseFile(FileChooserMode.Save)
                    File(content.value).writeText("this is save file")
                }
            }

            button("choose Single file") {
                action {
                    _chooseFile(FileChooserMode.Single)
                }
            }
            button("choose Multi file") {
                action {
                    _chooseFile(FileChooserMode.Multi)
                }
            }
            button("choose directory") {
                action {
                    chooseDirectory("choose dir",File(".")).apply {
                        this?.let {
                            content.value=it.absolutePath
                        }
                    }
                }
            }
        }

0 人点赞