CSS表格列的样式
为您的列添加适当的样式类:
nameColumn.getStyleClass().add("italic");
在您的场景中添加一个样式表,定义表格单元格的斜体样式:
.italic.table-cell { -fx-font-style: italic; }
注意1:
根据T-and-M Mike的评论,我再次尝试了这个示例,在搭载Java 8的OS X 10.9上并没有完全正常工作。在Windows上,仅将-fx-font-style
设置为italic即可使文本显示为斜体。但是在Mac上,这会将字体设置为System Italic,这是一种似乎不存在的字体,所以文本只能显示为非斜体。如果你还将字体族设置为已定义斜体的某种字体,那么列中的文本将按预期显示为斜体。例如,使用Times New Roman字体的斜体:
.italic.table-cell {
-fx-font-family: "Times New Roman";
-fx-font-style: italic;
}
注意事项2
在OS X 10.9上的Java 8b132中,当表格首次显示时存在轻微的渲染错误,表格内容与表头略微不对齐。
在表格显示在屏幕上后调用 table.requestLayout();
似乎可以修复表格的对齐渲染错误,但如果一切正常,此调用是不必要的。
可执行示例
在Win7 + Java 8b91上的测试输出结果:
CellShadedTable.java
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class CellShadedTable extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
stage.setTitle("So called friends . . .");
TableColumn<Friend, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<Friend, String>("name"));
nameColumn.setPrefWidth(75);
nameColumn.getStyleClass().add("italic");
TableColumn<Friend, String> owesMeColumn = new TableColumn<>("Owes Me");
owesMeColumn.setCellValueFactory(new PropertyValueFactory<Friend, String>("owesMe"));
owesMeColumn.setPrefWidth(150);
TableColumn<Friend, Boolean> willPayColumn = new TableColumn<>("Will Pay Up");
willPayColumn.setCellValueFactory(new PropertyValueFactory<Friend, Boolean>("willPay"));
willPayColumn.setPrefWidth(75);
TableView<Friend> table = new TableView(Friend.data);
table.getColumns().addAll(
nameColumn,
owesMeColumn,
willPayColumn
);
table.setPrefHeight(200);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
stage.setScene(new Scene(table));
stage.getScene().getStylesheets().add(getClass().getResource("cell-shader.css").toExternalForm());
stage.show();
table.requestLayout();
}
}
Friend.java
import javafx.collections.*;
public class Friend {
final static public ObservableList data = FXCollections.observableArrayList(
new Friend("George", "Movie Ticket", true),
new Friend("Irene", "Pay Raise", false),
new Friend("Ralph", "Return my Douglas Adams Books", false),
new Friend("Otto", "Game of Golf", true),
new Friend("Sally", "$12,045.98", false),
new Friend("Antoine", "Latte", true)
);
final private String name;
final private String owesMe;
final private boolean willPay;
public Friend(String name, String owesMe, boolean willPay) {
this.name = name; this.owesMe = owesMe; this.willPay = willPay;
}
public String getName() { return name; }
public String getOwesMe() { return owesMe; }
public boolean getWillPay() { return willPay; }
}
cell-shader.css
.italic.table-cell {
-fx-font-family: "Times New Roman";
-fx-font-style: italic;
}
基于单元格工厂的方法
关于自定义表格行颜色的 TableCell 方法,可以参考以下链接(对于简单的样式操作不是必需的):