Progressbar 在复制时更新进度

Progressbar update progress while copying

我想要一个来自 TornadoFX 的进度条,它知道它的最小值和最大值。

应该使用复制线程的信息来更新进度条:

 Files.copy(
    sourcePath,
    destinationPath,
    ExtendedCopyOption.INTERRUPTIBLE,
    StandardCopyOption.REPLACE_EXISTING
)

为了计算最大进度和当前进度,我使用了以下代码:

var mb = 1024
var fileSize = sourceFile.length() / mb
for (index in 0..fileSize) {
    updateMessage("Copying")
    updateProgress(index, fileSize)
    if (index == fileSize ) {
        updateMessage("Done"))
    }
}

总的来说,我已经缩短了很多。

button {
    action {
        runAsync {
            Files.copy(
               sourcePath,
               destinationPath,
               ExtendedCopyOption.INTERRUPTIBLE,
               StandardCopyOption.REPLACE_EXISTING
            )
            var mb = 1024
            var fileSize = sourceFile.length() / mb
            for (index in 0..fileSize) {
                updateMessage("Copying")
                updateProgress(index, fileSize)
                if (index == fileSize ) {
                    updateMessage("Done").get())
                }
            }
        }
    }
}

progressbar(status.progress) {
    progress = 0.0
    minWidth = 250.0
    minHeight = 30.0
}

每个异步操作都会更新默认的 TaskStatus 模型,因此基本上您只需将 TaskStatus 模型注入视图并将其绑定到 ProgressBar。 TaskStatus 具有 runningcompletedmessagetitleprogress.

的可观察属性

我写了一篇短文,并在实现时创建了一个截屏视频,您可能会觉得很有趣:

https://edvin.town/tornadofx-runasync-with-taskstatus/

您还可以传入特定的 TaskStatus 实例,甚至可以在需要时重用用于实现此目的的模式。实现细节见框架源码