我有一个简单的场景与此代码:
scene.getStylesheets().add("packagename/testcss.css");
Run Code Online (Sandbox Code Playgroud)
我的testcss.css是:
.button {
-fx-background-color: #DDFFA4;
}
.button:hover {
-fx-background-color: #9ACD32;
}
Run Code Online (Sandbox Code Playgroud)
我所取得的成就是在Web应用程序中徘徊的好效果.
... 
问题
如何通过我的Button的setStyle方法实现相同的效果,但没有单独的css文件?
问题是setStyle只接受样式定义并省略了选择器.
button.setStyle("-fx-background-color: #DDFFA4;");
Run Code Online (Sandbox Code Playgroud)
我的悬停情况下的选择器是伪类:
.button:hover
Run Code Online (Sandbox Code Playgroud)
但我应该在哪里设置它?
此外,javadoc在从setStyle方法参数中排除选择器时是显式的:
请注意,与HTML样式属性一样,此变量包含样式属性和值,而不是样式规则的选择器部分.
jew*_*sea 28
正如您在问题中所述,从JavaFX 2.2开始,css伪类不会作为公共API的一部分公开,您可以将其用于Java代码中的样式操作.
如果要在不使用样式表的情况下从Java代码更改样式属性,则需要根据事件或changelisteners设置样式.下面的示例中有几个选项.
import javafx.application.Application;
import javafx.beans.binding.*;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
/** Changing button styles on hover without a css stylesheet. */
public class ButtonBackgroundChanger extends Application {
private static final String STANDARD_BUTTON_STYLE = "-fx-background-color: #DDFFA4;";
private static final String HOVERED_BUTTON_STYLE = "-fx-background-color: #9ACD32;";
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
Button configure = new Button("Configure");
changeBackgroundOnHoverUsingBinding(configure);
Button update = new Button("Update");
changeBackgroundOnHoverUsingEvents(update);
VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER);
layout.setStyle("-fx-padding: 10;");
layout.getChildren().addAll(configure, update);
stage.setScene(new Scene(layout));
stage.show();
}
private void changeBackgroundOnHoverUsingBinding(Node node) {
node.styleProperty().bind(
Bindings
.when(node.hoverProperty())
.then(
new SimpleStringProperty(HOVERED_BUTTON_STYLE)
)
.otherwise(
new SimpleStringProperty(STANDARD_BUTTON_STYLE)
)
);
}
public void changeBackgroundOnHoverUsingEvents(final Node node) {
node.setStyle(STANDARD_BUTTON_STYLE);
node.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent mouseEvent) {
node.setStyle(HOVERED_BUTTON_STYLE);
}
});
node.setOnMouseExited(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent mouseEvent) {
node.setStyle(STANDARD_BUTTON_STYLE);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我只是在代码而不是样式表中真正做到这一点,如果颜色需要真正动态地使用具有预定义颜色和样式的样式表有问题,或者如果有其他厌恶使用css样式表.
在JavaFX 8中,有一个公共API,允许您(如果您愿意)在不使用CSS的情况下操作Region背景颜色.
示例程序输出(更新按钮悬停):

| 归档时间: |
|
| 查看次数: |
24629 次 |
| 最近记录: |