我构建了一个基于 Java Swing 的游戏(黑白棋又名黑白棋,学生元素)。 通过菜单栏中的 ColorChooser,我让用户可以为背景、球场和球员选择单独的颜色。
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);});
使用的颜色保存在数组“colors”中,通过一些方法调用选择的颜色被设置。
void change_colors(Color[] colors)
{
this.colors = colors;
this.setBackground(colors[1]);
}
一切正常。
现在我正在构建一个 Java Fx 等价物。我不使用 FXML 或 Scene Builder,但我尝试使用 CSS 文件设置样式。
//.java
this.getStylesheets().add("Fx_GUI/Style.css");
this.getStyleClass().add("cell");
//.css
.cell
{
-fx-background-color: rgb(34, 139, 34);
}
我的问题:是否有一种基于 css 的方法可以获得相同的效果,为我的组件设置单独的颜色集?例如在 .css 中使用变量或类似的东西?
最佳答案
您可以使用 looked-up colors (向下滚动到颜色方 block 之外以查看查找颜色的描述):
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));
关于Javafx 用户选择颜色 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40567291/