【发布时间】:2016-12-25 23:35:28
【问题描述】:
我有一个使用许多复选框的 javafx 应用程序。当一个复选框被选中时,一个按钮将出现在主窗口中。复选框设置为“false”使按钮消失。很容易。
问题是复选框不记得它被选中并且应用程序总是以选中的复选框开始,如 fxml 文件中定义的那样:
<CheckBox fx:id="googleHider" onAction="#hideGoogle" selected="true" text="Google">
由于我在 Google 上找不到任何令人满意的东西,我想出了一个自制的解决方案,设置一个函数,直接在 fxml 文档中将复选框的选中状态设置为“true”或“false”,这很有效完美。
我只是想知道这是否是一种简单有效的良好做法,或者是否有人已经找到或可以想象出更优雅或更简约的解决方案。 (我之前的编程经验更多的是Python,不知道有没有表现出来。有没有更“Javaian”的方式……?)
boolean isSelected = googleHider.isSelected();
if (isSelected == false) {
System.out.println("not selected");
Path path = Paths.get("src/javafxapplication2/PopupFXML.fxml");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path));
//following line changes the initial state of the checkbox from "true" to "false"
content = content.replaceAll("\"#hideGoogle\" selected=\"true\"", "\"#hideGoogle\" selected=\"false\"");
Files.write(path, content.getBytes(charset));
}
else {
System.out.println("selected");
Path path = Paths.get("src/javafxapplication2/PopupFXML.fxml");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path));
// next line changes the state back from "false" to "true"
content = content.replaceAll("\"#hideGoogle\" selected=\"false\"", "\"#hideGoogle\" selected=\"true\"");
Files.write(path, content.getBytes(charset));
}
【问题讨论】:
-
虽然我喜欢你的方法,因为它是开箱即用的,但我仍然认为更清晰的方法是创建一个设置文件,然后在启动时从文件中读取值并关机时将值保存到文件中
-
好主意,这个设置文件在 javafx 应用程序中的理想位置是什么?它会是一个txt.file吗?您知道任何文档或更清晰的方向吗?
-
@Rainer 至于位置,用户主目录似乎是一个显而易见的选择...stackoverflow.com/questions/585534/…