dimanche 25 décembre 2016

What is the best way to make a checkbox remember it's state?

I have a javafx application that uses many checkboxes. When a checkbox is selected, a button will appear in the main window. Checkbox set to "false" makes the button disappear. Easy enough.

Problem is that the checkbox does not remember that it was checked and the application always starts with the checkboxes selected, as defined in the fxml file:

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

Since I couldn't find anything satisfying on Google, I came up with a homegrown solution, setting up a function that sets the selected state of the checkbox to "true" or "false" directly in the fxml document, which works perfectly.

I just wonder if this is good practice, simple and effective, or if somebody has found or can imagine a more elegant or minimalistic solution. (My previous programming experience is more in Python, I don't know if it shows. Is there a more "Javaian" way...?)

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

    }




Aucun commentaire:

Enregistrer un commentaire