Abgehter Abgehter - 21 days ago 11
CSS Question

Java Fx Userchoosen color CSS

I built a Java Swing based Game (Reversi aka Othello, student-project).
Via ColorChooser in the MenuBar i gave the User the possibility to choose individual colors for the background, the court and the players.

this.menu_bar.bg_color.addActionListener(e -> { Color buffer = colors[0];
colors[0] = JColorChooser.showDialog(null, "Hintergrundfarbe", colors[0]);
if (colors[0] == null)
colors[0] = buffer;
else
this.frame.change_colors(colors);});


The used colors are saved in the array "colors", along some methodcalls the choosen color gets set.

void change_colors(Color[] colors)
{
this.colors = colors;
this.setBackground(colors[1]);
}


All works fine.

Now Im buiding an Java Fx equivalent. I dont use FXML or Scene Builder, but I try to style with CSS-file.

//.java
this.getStylesheets().add("Fx_GUI/Style.css");
this.getStyleClass().add("cell");

//.css
.cell
{
-fx-background-color: rgb(34, 139, 34);
}


My question: Is there a css-based way to get the same effect possible, to set an individual color set for my components? For example use variables in the .css or something like this?

Answer

You can use looked-up colors (scroll down beyond the color squares for the description of looked-up colors):

CSS:

.root {
    /* default value */
    -cell-background: rgb(34, 139, 34);
}
.cell {
    -fx-background-color: -cell-background ;
}

Java:

this.getStylesheets().add("Fx_GUI/Style.css");
this.getStyleClass().add("cell");

// ...

int r = ... ;
int g = ... ;
int b = ... ;
this.setStyle(String.format("-cell-background: rgb(%d, %d, %d);", r, g, b));
Comments