TornadoFX filechooser
TornadoFX filechooser
I am looking solution for javafx FileChooser(in Kotlin). I stuck on this, I cannot pass root View, because Window! is expected:
FileChooser
Window!
button("open some file") {
setOnAction {
val fileChooser = FileChooser();
val file = fileChooser.showOpenDialog(???)
...
}
}
What should I pass in this case?
chooseFile
chooseDirectory
primaryStage
openModal
openWindow
modalStage
View
Stage
Window
3 Answers
3
According to the docs you can pass a null for the window.
null
If the owner window for the file dialog is set, input to all windows in the dialog's owner chain is blocked while the file dialog is being shown.
However, since you are using TornadoFX, you may instead just want to use the chooseFile and chooseDirectory functions it provides. They automatically handle the hairy parts for you with useful defaults, but (since they are only defaults after all) you can easily override them to tailor the functionality to your needs.
chooseFile
chooseDirectory
The following code worked for me:
with(root) {
button("Target Directory") {
action {
var dir = chooseDirectory("Select Target Directory")
}
}
}
On Windows, the file chooser dialogue will open "My Computer" by default.
You can get Window by root.scene.window (node.getScene().getWindow())
working example for file choosers:
import tornadofx.*
import javafx.scene.control.TextArea
import javafx.scene.control.TextField
import javafx.stage.FileChooser
import java.io.File
class FileChooserView : View() {
override val root = borderpane()
private val ef = arrayOf(FileChooser.ExtensionFilter("Audio files (*.mp3, *.wav)", "*.mp3", "*.wav"))
private lateinit var tfFN: TextField
private lateinit var tfFA: TextArea
init {
with(root) {
title = "FileChooserView"
center = form {
fieldset("File Choosers") {
field("File w/o block parent") {
hbox {
tfFN = textfield()
button("open") {
action {
val fn: List<File> = chooseFile("Single + non/block",ef, FileChooserMode.Single)
if (fn.isNotEmpty()) {
tfFN.text = "${fn.first()}"
}
}
}
}
}
field("Files with block parent") {
hbox {
tfFA = textarea()
button("open") {
action {
val fn: List<File> = chooseFile("Multi + block", ef, FileChooserMode.Multi, root.scene.window)
if (fn.isNotEmpty()) {
tfFA.text = "$fn"
}
}
}
}
}
}
}
}
}
}
class FileChooserApp : App(FileChooserView::class) {}
fun main(args: Array<String>) { launch<FileChooserApp>(args) }
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Although Ruckus gave you the correct answer below (use the
chooseFileandchooseDirectoryfunctions in TornadoFX), I just wanted to point out that you can access the stage via theprimaryStageproperty. If your View is opened usingopenModaloropenWindowyou can access your stage via themodalStageproperty of theView.Stageinherits fromWindow.– Edvin Syse
Nov 22 '16 at 8:19