我正在尝试编写一个代码,该代码将在控制台中打印所选文件的路径。我读过有关范围的内容,所以我尝试使用它们,但我想,还没有很好地理解它们。这是主窗口的控制器和视图的代码:
class MainController : Controller() {
var filePath : String? = null
fun startup() {
class filenameScope : Scope() {
val filenameModel = FilenameModel()
}
println(filePath.toString() + " 1") // These prints are for test purposes,
val scope = filenameScope() // ideally after the second print
find<PopupFragment>(scope).openModal() // it returns file path
filePath = scope.filenameModel.fileName.value
println(filePath.toString() + " 2")
}
}
class MainView: View("Shape modifier") {
val controller : MainController by inject()
val label = Label()
override val root = vbox()
init {
with(root) {
this += label
this += button("Big button") {
action {
print(controller.filePath)
}
}
}
}
}
文件名数据和文件名模型:
class FilenameData() {
val filenameProperty = SimpleStringProperty()
}
class FilenameModel : ItemViewModel<FilenameData>(FilenameData()) {
var fileName = bind(FilenameData::filenameProperty)
}
最后,片段的观点:
class PopupFragment : View("Choose or create new list") {
val controller: PopupController by inject()
val model : FilenameModel by inject()
override val root = vbox {
button("Browse") {
action {
val filters = arrayOf(FileChooser.ExtensionFilter("JSON file", "*.json"))
try {
model.fileName.value = chooseFile("Open JSON file", filters)[0].absolutePath.toString()
} catch (e: Exception) {
}
}
}
}
}
结果,我从 MainController
和在片段中选择文件后得到了空值。我可以怀疑问题出在片段的按钮操作中,但我不明白。