问题描述:我无法在JavaFX中获得对象的背景.我不是指形状,而是像Buttons,Tabs等常规节点.我不知道如何访问他们的背景颜色.
我想要的是?我正在开发IDE,我想在选项卡上运行Color动画,文件是用户想要打开的,并且已经存在于程序文件集合中.在做这个动画之前,我想阅读原始标签背景颜色,并在动画结束时将颜色返回到标签.此外,我想回到悬停和选定的属性,当我在动画中设置一些颜色并且它们永远不会回来时它会消失.我在CSS文件中设置的所有颜色,我不想更改它.
我的问题:如何以编程方式获取和设置节点颜色?或者如何使用保存原始属性进行颜色动画,并在动画结束时获取此属性?
一个简短的例子:
sample.fxml
styles.css的
.tab{
-fx-background-color: pink;}
.tab:hover{
-fx-background-color: red;}
.tab:selected{
-fx-background-color: yellow;}
解决方法:
据我所知,公共API中没有办法确定当前用作区域(包括控件)的背景颜色(除非你知道它是由内联样式设置的,在这种情况下)你可以解析getStyle()的结果或通过调用setBackground(…)来解析.但我认为没理由你会想要这个;如果删除任何内联样式或背景属性,颜色将恢复为css文件中定义的颜色.
这是一个简单的示例,其中背景颜色由线性渐变(通过内联样式)设置,随着任务的进行滑动:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ColoredTabDemo extends Application {
private int tabCount ;
@Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
for (int i = 0; i < 4; i++) {
tabPane.getTabs().add(createTab());
}
Scene scene = new Scene(tabPane, 600, 400);
scene.getStylesheets().add("colored-tab-demo.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private Tab createTab() {
Tab tab = new Tab("Tab "+(++tabCount));
Button button = new Button("Load file...");
button.setOnAction(e -> {
Task task = new Task() {
@Override
public Void call() throws Exception {
// simulate loading:
for (int i=1; i <= 500; i++) {
updateProgress(i, 500);
Thread.sleep(20);
}
return null ;
}
};
IntegerBinding progressAsPercent = Bindings.createIntegerBinding(() ->
(int) (task.getProgress() * 100), task.progressProperty());
tab.styleProperty().bind(Bindings.format("-fx-background-color: "
+ "linear-gradient(to right, -fx-accent 0%%, -fx-accent %d%%, -fx-background %1$d%%, -fx-background 100%%);",
progressAsPercent));
button.setDisable(true);
task.setOnSucceeded(evt -> {
tab.styleProperty().unbind();
tab.setStyle("");
button.setDisable(false);
});
new Thread(task).start();
});
tab.setContent(new StackPane(button));
return tab ;
}
public static void main(String[] args) {
launch(args);
}
}
colored-tab-demo.css与您发布的几乎完全相同,但使用查找颜色而不是直接设置-fx-background-color:
.tab{
-fx-background-color: -fx-background;
-fx-background: pink ;
}
.tab:hover{
-fx-background: red;
}
.tab:selected{
-fx-background: yellow;
}
标签:java,javafx,animation,background,colors
来源: https://codeday.me/bug/20191008/1873236.html