使复选框记住它的状态的最佳方法是什么?

时间:2016-12-25 14:09:25

标签: java checkbox javafx

我有一个使用许多复选框的javafx应用程序。选中复选框后,主窗口中将出现一个按钮。复选框设置为" false"使按钮消失。很容易。

问题是复选框不记得它已被选中,并且应用程序始终以选中的复选框开始,如fxml文件中所定义:

<CheckBox fx:id="googleHider" onAction="#hideGoogle" selected="true" text="Google">

由于我无法在Google上找到满意的内容,因此我想出了一个自行开发的解决方案,设置了一个功能,可以将复选框的选定状态设置为&#34; true&#34;或&#34;假&#34;直接在fxml文档中,它可以很好地工作。

我只是想知道这是不是很好的做法,简单有效,或者是否有人找到或可以设想更优雅或简约的解决方案。 (我之前的编程经验更多的是Python,我不知道它是否显示。是否还有更多的#Java; Javaian&#34;方式......?)

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));

    }

2 个答案:

答案 0 :(得分:2)

我肯定会使用设置文件。这样的设置文件不应该位于您的应用程序中,因为您无法在执行时修改应用程序。好的位置是AppData文件夹(在Windows上)或用户目录(在linux和mac上)或保存应用程序的文件夹。

我编写了一个创建*.properties文件的小型库,并将它们保存在AppData文件夹中(如果不在Windows上,则保存在用户目录中),您也可以使用它:Common

答案 1 :(得分:2)

您可以使用SharedPrefrences创建.putBoolean()并添加值。

if(ch.isSelected()){             

SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME, 0);
settings.edit().putBoolean("check",true).commit();
}

你可以通过多种方式做到这一点。在下面提供的链接中,您将了解用户会话管理的基本概念以及活动之间的共享数据。

http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/