Issue
Does anyone know how I could simplyfy these two lines? I have heard something about .setAll but I don't really know how to do this.
parent.getStylesheets().remove(String.valueOf(getClass().getResource("/css/darkmode.css")));
parent.getStylesheets().add(String.valueOf(getClass().getResource("/css/lightmode.css")));
Solution
To answer your question simply: No. Maybe it is only my limited knowledge, but it is generally better practice to keep it long. The CSS sheet could be set for the entire scene rather than the parent.
It is best to use the getClass().getResource(...)
as, at build time, the file reference is still valid. If you were to try and shorten the reference and perhaps direct it at a file location, it will not be properly accessed. You must ensure that the css files are within the src/main/resources/
folder. I have found it needed to be outside of a sub folder, but that might have been my problem.
I tackled a dark and light mode recently myself. I have an example here of how I set the dark/light mode in my project, but it really depends on the architecture you are using; here I am using MVC (Model View Controller). If you leave more information and notify me with a comment, I could update my answer.
In MainView.java
,
/*
* Parameters:
* - dark: a boolean value of dark or not
* Function: Alters the theme of light or dark
* Returns: Void
*/
public void setDark(boolean dark) {
if (dark) {
scene.getStylesheets().add(getClass().getResource("design-DARK.css").toExternalForm());
scene.getStylesheets().remove(getClass().getResource("design-LIGHT.css").toExternalForm());
} else {
scene.getStylesheets().add(getClass().getResource("design-LIGHT.css").toExternalForm());
scene.getStylesheets().remove(getClass().getResource("design-DARK.css").toExternalForm());
}
}
In MainModel.java
,
private Boolean isDark = false;
/*
* Parameters: None
* Function: Switches between light and dark mode
* Returns: Void
*/
public void alterDark() {
if (isDark) {
isDark = false;
view.setDark(false);
} else {
isDark = true;
view.setDark(true);
}
}
Answered By - ConnerWithAnE
Answer Checked By - Cary Denson (JavaFixing Admin)