如何轻松将自定义(可重复使用)cellFactories应用于javafx.scene.control.TableCell;
或javafx.scene.control.TableView;
?
答案 0 :(得分:13)
要应用自定义CellFactories格式化单元格中显示的文本,其颜色等,以下示例可能是很好的帮助。
假设你有一个Bean / POJO Person
:
public class Person {
private double levelOfGrowth = 0;
public Person() {};
public Person(double levelOfGrowth) {
this.levelOfGrowth = levelOfGrowth;
};
public double getLevelOfGrowth() {
return levelOfGrowth;
}
}
levelOfGrowth
是指一个人的成长完成程度的百分比值。
可能设置在0.00到1.00之间。
让我们假设您已在FXML中创建了视图,该视图绑定到控制器MainWindowController
。您还可以将列设置为显示levelOfGrowth
到ID levelOfGrowthColumn
public class MainWindowController implements Initializable {
@FXML
public TableColumn levelOfGrowthColumn;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<Person> persons = FXCollections.observableArrayList();
persons.add(new Person(0));
persons.add(new Person(0.5));
persons.add(new Person(1));
levelOfGrowthColumn.setCellValueFactory(new PropertyValueFactory<Person, Double>("levelOfGrowth"));
}
}
上面示例中的问题是视图中显示的值类似于0.5而不是50%。我们也可能希望将值100%的颜色更改为绿色。
我们需要的是一个(可重用)类,它描述了如何在视图中格式化/打印双值并将该类与levelOfGrowthColumn
连接起来。
public class PercantageFormatCell extends TableCell<Object, Double> {
public PercantageFormatCell() {
}
@Override
protected void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
// If the row is not empty but the Double-value is null,
// we will always display 0%
if (!empty && null == item) {
item = new Double(0.0d);
}
// Here we set the displayed text to anything we want without changing the
// real value behind it. We could also have used switch case or anything you
// like.
setText(item == null ? "" : NumberFormat.getPercentInstance().format(item));
// If the cell is selected, the text will always be white
// (so that it can be read against the blue background),
// if the value is 1 it will be green.
if (item != null) {
double value = item.doubleValue();
if (isFocused() || isSelected() || isPressed()) {
setTextFill(Color.WHITE);
} else if (value < 1) {
setTextFill(Color.BLACK);
} else {
setTextFill(Color.GREEN);
}
}
}
}
public class MainWindowController implements Initializable {
@FXML
public TableColumn levelOfGrowthColumn;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList<Person> persons = FXCollections.observableArrayList();
persons.add(new Person(0));
persons.add(new Person(0.5));
persons.add(new Person(1));
// New code START
// In case we have multiple columns with percent-values it
// might come in handy to store our formatter
Callback<TableColumn, TableCell> percantageCellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new PercantageFormatCell();
}
};
// Now all we have to do is to apply it
levelOfGrowthColumn.setCellFactory(percantageCellFactory);
// New code END
levelOfGrowthColumn.setCellValueFactory(new PropertyValueFactory<Person, Double>("levelOfGrowth"));
}
}