在运行的Java应用程序中更改CSS样式的方法

时间:2019-05-10 02:21:10

标签: java css javafx

我正在使用JavaFX应用程序,该应用程序使用文件中包含的CSS样式。我想要的是在按钮上发生动作后更改CSS样式,并编写了一些代码,当我输入/退出它时,它们会更改Button的样式:

public void actionMouseEntered() {
    buttonReflex1.getStyleClass().clear();
    buttonReflex1.getStyleClass().add("button_reflex_pressed");
    }
public void actionMouseExited(){
    buttonReflex1.getStyleClass().clear();
    buttonReflex1.getStyleClass().add("button_reflex");
}

这是我的CSS文件:

.button_reflex{
    -fx-shape: "M 200 *a lot of numbers here* Z";
    -fx-background-color: radial-gradient(focus-angle 360deg, focus-distance 0%, center 50% 50%, radius 70%, reflect, lightblue, aqua 30%, blue);
    -fx-text-fill: linear-gradient(#e4e000 0%, #ff0000 50%, #e4e000 100%);
}
.button_reflex_pressed{
    -fx-shape: "M 200 *a lot of numbers here* Z";
    -fx-background-color: radial-gradient(focus-angle 360deg, focus-distance 0%, center 50% 50%, radius 70%, reflect, dodgerblue, deepskyblue 30%, darkblue);
    -fx-text-fill: linear-gradient(#e4e000 0%, #ff0000 50%, #e4e000 100%);
}

它们的按钮颜色不同。

我在 WORKS 上面编写的代码,但我认为我编写的方式不是很好。您能告诉我我实施该方法的方法是否正确,请告诉我我该如何做得更好,因为我不想学习不良习惯。

2 个答案:

答案 0 :(得分:4)

您不需要更改样式类。更改样式类也不是解决此问题的最佳方法。在这种情况下,应使用PseudoClass。另外,您应该避免复制没有不同或仅颜色不同的css属性。为这两者使用规则仅一次指定此名称,以使其易于修改;在后一种情况下,您可以使用查阅颜色:

private static final PseudoClass MY_HOVER = PseudoClass.getPseudoClass("my-hover");

...
buttonReflex1.getStyleClass().setAll("button-reflex");
...

    boolean hovering = ...;
    buttonReflex1.pseudoClassStateChanged(MY_HOVER, hovering);
.button-reflex {
    -fx-background-color1: lightblue;
    -fx-background-color2: aqua;
    -fx-background-color3: blue;
    -fx-shape: "M 200 *a lot of numbers here* Z";
    -fx-background-color: radial-gradient(focus-angle 360deg, focus-distance 0%, center 50% 50%, radius 70%, reflect, -fx-background-color1, -fx-background-color2 30%, -fx-background-color3);
    -fx-text-fill: linear-gradient(#e4e000 0%, #ff0000 50%, #e4e000 100%);
}

.button-reflex:my-hover {
    /* only change colors here; keep the rest */
    -fx-background-color1: dodgerblue;
    -fx-background-color2: deepskyblue;
    -fx-background-color3: darkblue;
}

注意my-hover伪类仅在此处用于演示通用方法。默认情况下,JavaFX Node提供了一些伪类,应该使用它们来代替:hoverpressed等...

请参见JavaFX CSS Reference Guide: Node

答案 1 :(得分:1)

首先,是的,您可以在运行时更改CSS。

但是您使用它的方式有误。

因此,如果您有Node的基本CSS类。 例如:

.button {
    -fx-background-color: red;
}

现在,如果您想对任何JavaFx Event产生影响,则可以使用悬停,按下,聚焦...

.button {
   -fx-background-color: red;
}

.button:hover {
   -fx-background-color: blue;
}

.button:pressed{
   -fx-background-color: green;
}

JavaFx不仅可以为您处理所有事情,而且您无需手动更改样式。