Reputation: 3411
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));
}
Upvotes: 2
Views: 970
Reputation: 999
You can create SharedPrefrences
and add value using .putBoolean()
.
if(ch.isSelected()){
SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME, 0);
settings.edit().putBoolean("check",true).commit();
}
You can do that in many ways. In the link provided below, you will understand the basic concept of user session management and sharing data among activites.
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
Upvotes: 2
Reputation: 3119
I would definnitely use a settings file. Such a settings file should not be located in your application as you cannot always modify your application while it is beeing executed. Good locations are the AppData folder (on windows) or the user directory (on linux and mac) or the folder where the application is saved in.
I wrote a small library that creates *.properties
-files and saves them in the AppData folder (or the user directory if not on windows), you can use it too: Common
Upvotes: 2