我需要创建具有多色行的 JavaFx TableView(color1 用于低优先级,color2 用于中等优先级等)。我创建了 CellFactory
public class TaskCellFactory implements Callback<TableColumn, TableCell> {
@Override
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<Task, Object>() {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
TableRow currentRow = getTableRow();
Task currentTask = currentRow == null ? null : (Task)currentRow.getItem();
if(currentTask != null){
Priority priority = currentTask.getPriority();
clearPriorityStyle();
if(!isHover() && !isSelected() && !isFocused()){
setPriorityStyle(priority);
}
}
}
@Override
public void updateSelected(boolean upd){
super.updateSelected(upd);
System.out.println("is update");
}
private void clearPriorityStyle(){
ObservableList<String> styleClasses = getStyleClass();
styleClasses.remove("priorityLow");
styleClasses.remove("priorityMedium");
styleClasses.remove("priorityHigh");
}
private void setPriorityStyle(Priority priority){
switch(priority){
case LOW:
getStyleClass().add("priorityLow");
break;
case MEDIUM:
getStyleClass().add("priorityMedium");
break;
case HIGH:
getStyleClass().add("priorityHigh");
break;
}
System.out.println(getStyleClass());
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
return cell;
} }
和CSS
.priorityLow{ -fx-background-color: palegreen; }
.priorityMedium{ -fx-background-color: skyblue;}
.priorityHigh{ -fx-background-color: palevioletred;}
但我仍然需要突出显示选定的行。我该怎么做?
最佳答案
无需在您的 css 中为整个单元格设置背景颜色,只需设置 -fx-control-inner-background。然后您将仍然可以使用默认重音、悬停和对焦环。当然,还要删除 setPriorityStyle
调用周围的 if 语句。
如果您还想覆盖默认重音(选定)颜色或悬停颜色等内容,您也可以按照下面的 css 执行此操作 - 不确定是否真的推荐高亮覆盖,我猜这取决于您的应用和所需的用户体验。
.priorityLow {
-fx-control-inner-background: palegreen;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
.priorityMedium {
-fx-control-inner-background: skyblue;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
.priorityHigh {
-fx-control-inner-background: palevioletred;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}
JavaFX 的详细样式信息可以在默认 caspian.css stylesheet 中找到对于 JavaFX 2.2 和 JavaFX 2 CSS reference guide .要为您的 JavaFX 版本找到 caspian.css,您可以解压 jfxrt.jar
(有时可以在 jre/lib 目录中找到)。
更新
JavaFX 的默认样式表现在命名为 modena.css
而不是 caspian.css
。
关于JavaFX 表格 View 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13697115/