我为我创建的每个对象都有一个ReadOnlyBooleanProperty命名。每个对象填充表视图中的一行。现在我希望表行在 时保持橙色闪烁。cautionTradeTradecautiontrue
public class Trade{
private DoubleProperty volume;
private ReadOnlyBooleanWrapper caution;
public Trade(double volume){
this.volume = new SimpleDoubleProperty(volume);
this.caution = new ReadOnlyBooleanWrapper();
this.caution.bind(this.volume.greaterThan(0));
}
}
Run Code Online (Sandbox Code Playgroud)
只要属性为真,如何使表行永远闪烁caution?
要使某些内容闪光,请使用Timeline:
Timeline flasher = new Timeline(
new KeyFrame(Duration.seconds(0.5), e -> {
// use "flash" color
}),
new KeyFrame(Duration.seconds(1.0), e -> {
// revert to regular color
})
);
Run Code Online (Sandbox Code Playgroud)
在这种情况下更改颜色的最佳方法是使用CSSPseudoClass:
PseudoClass flashHighlight = PseudoClass.getPseudoClass("flash-highlight");
Node flashingNode = ... ;
Timeline flasher = new Timeline(
new KeyFrame(Duration.seconds(0.5), e -> {
flashingNode.pseudoClassStateChanged(flashHighlight, true);
}),
new KeyFrame(Duration.seconds(1.0), e -> {
flashingNode.pseudoClassStateChanged(flashHighlight, false);
})
);
flasher.setCycleCount(Animation.INDEFINITE);
Run Code Online (Sandbox Code Playgroud)
然后在外部 CSS 文件中,您可以配置 Flash 高亮的样式:
.node-type:flash-highlight {
/* style for flash "on" */
}
Run Code Online (Sandbox Code Playgroud)
要将其绑定到布尔属性,您只需使用以下属性创建一个侦听器:
someBooleanProperty.addListener((obs, oldValue, newValue) -> {
if (newValue) {
flasher.play();
} else {
flasher.stop();
flashingNode.pseudoClassStateChanged(false);
}
});
Run Code Online (Sandbox Code Playgroud)
要将其应用到表行,您必须编写一个rowFactory. 您只需要注意,行中显示的项目可能会在行的生命周期内发生变化,因此您需要相应地更新状态和侦听器:
TableView<Trade> table = ... ;
PseudoClass flashHighlight = PseudoClass.getPseudoClass("flash-highlight");
table.setRowFactory(tv -> {
TableRow<Trade> row = new TableRow<>();
Timeline flasher = new Timeline(
new KeyFrame(Duration.seconds(0.5), e -> {
row.pseudoClassStateChanged(flashHighlight, true);
}),
new KeyFrame(Duration.seconds(1.0), e -> {
row.pseudoClassStateChanged(flashHighlight, false);
})
);
flasher.setCycleCount(Animation.INDEFINITE);
ChangeListener<Boolean> cautionListener = (obs, cautionWasSet, cautionIsNowSet) -> {
if (cautionIsNowSet) {
flasher.play();
} else {
flasher.stop();
row.pseudoClassStateChanged(flashHighlight, false);
}
};
row.itemProperty().addListener((obs, oldItem, newItem) -> {
if (oldItem != null) {
oldItem.cautionProperty().removeListener(cautionListener);
}
if (newItem == null) {
flasher.stop();
row.pseudoClassStateChanged(flashHighlight, false);
} else {
newItem.cautionProperty().addListener(cautionListener);
if (newItem.cautionProperty().get()) {
flasher.play();
} else {
flasher.stop();
row.pseudoClassStateChanged(flashHighlight, false);
}
}
});
return row ;
});
Run Code Online (Sandbox Code Playgroud)
然后定义一个外部 CSS 文件,类似于
.table-row-cell:flash-highlight {
-fx-background: orange ;
}
Run Code Online (Sandbox Code Playgroud)
以及您想要的任何其他风格。