如何在java fx的表视图中将字体设置为列.我有一个包含3列的表,我想为每个列设置不同的字体.此外,是否可以在运行时更改字体.请帮助您提供一些示例代码.
Ulu*_*Biy 13
您应该使用TableColumn #setCellFactory()来自定义单元格项呈现.
例如,像这个Person类的 datamodel :
// init code vs..
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setCellFactory(getCustomCellFactory("green"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setCellFactory(getCustomCellFactory("red"));
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
// scene create code vs..
Run Code Online (Sandbox Code Playgroud)
和常用getCustomCellFactory()方法:
private Callback<TableColumn<Person, String>, TableCell<Person, String>> getCustomCellFactory(final String color) {
return new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
@Override
public TableCell<Person, String> call(TableColumn<Person, String> param) {
TableCell<Person, String> cell = new TableCell<Person, String>() {
@Override
public void updateItem(final String item, boolean empty) {
if (item != null) {
setText(item);
setStyle("-fx-text-fill: " + color + ";");
}
}
};
return cell;
}
};
}
Run Code Online (Sandbox Code Playgroud)
TableView与JavaFX的其他控件一样,它使用caspian.css与jfxrt.jar捆绑在一起的内置样式表.请参阅"JavaFX 2和CSS类"的答案.
要更改列字体样式,您可以覆盖默认样式或自定义它:
覆盖:
.table-view .column-header{
-fx-text-fill: -fx-selection-bar-text;
-fx-font-size: 16;
-fx-font-family: "Arial";
}
Run Code Online (Sandbox Code Playgroud)
定制:
#my-custom .table-view .column-header {
-fx-text-fill: red;
-fx-font-size: 26;
-fx-font-family: "Arial";
}
Run Code Online (Sandbox Code Playgroud)
覆盖所有TableView应用程序中的效果.因此,如果您希望自定义,则在定义多个样式后,可以在运行时将自定义样式应用于任何tableview,
myTableView.setId("my-custom");
...
// Apply another style at runtime
myTableView.setId("my-custom2");
Run Code Online (Sandbox Code Playgroud)
要了解如何定义样式表文件并将其加载到应用程序,请查看"JavaFX如何设置场景背景图像"的帖子.
但是,我认为将不同的样式应用于不同的列需要更多的努力.
| 归档时间: |
|
| 查看次数: |
29824 次 |
| 最近记录: |