JavaFX tableview颜色

我需要创建具有多色行的JavaFx TableView(color1用于低优先级,color2用于中等优先级等)。 我创建了CellFactory

public class TaskCellFactory implements Callback { @Override public TableCell call(TableColumn p) { TableCell cell = new TableCell() { @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 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即可。 然后您将拥有默认重音,hover和对焦环仍然可用。 当然也要删除setPriorityStyle调用周围的if语句。

如果您还想覆盖默认重音(选定)颜色或hover颜色等内容,您也可以在下面的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%); } 

rowhighlight


JavaFX的详细样式信息可以在JavaFX 2.2的默认caspian.css样式表和JavaFX 2 CSS参考指南中找到 。 要为您的JavaFX版本找到caspian.css,您可以解开jfxrt.jar (有时可以在jre / lib目录中找到)。