JavaFXTableView,如何在同一工厂中添加侦听器和覆盖updateItem
我目前正在进行一个带有TableView元素的小型学习项目。我正在根据每行的内容更改其背景色,如下所示:JavaFXTableView,如何在同一工厂中添加侦听器和覆盖updateItem,java,javafx,Java,Javafx,我目前正在进行一个带有TableView元素的小型学习项目。我正在根据每行的内容更改其背景色,如下所示: TableView.setRowFactory((row) -> new TableRow<Person>() { @Override public void updateItem(Person person, boolean empty) { super.updateItem(person, empty); switch (person.getPers
TableView.setRowFactory((row) -> new TableRow<Person>() {
@Override
public void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
switch (person.getPersonStatus()) {
case ST:
setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
case CD:
setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
}
}
TableView.setRowFactory((行)->newtableRow(){
@凌驾
public void updateItem(Person,布尔值为空){
super.updateItem(person,空);
开关(person.getPersonStatus()){
案例ST:
setStyle(“-fx控件内部背景:“+StatusColor.B_LIGHT.getMyColorValue()+”;-fx文本填充:#fff;”);
打破
案例CD:
setStyle(“-fx控件内部背景:“+StatusColor.D_LIGHT.getMyColorValue()+”;-fx文本填充:#fff;”);
打破
}
}
此外,我还希望在双击该行时获得该行中对象的引用。为此,我使用以下代码:
TableView.setRowFactory((row) -> {
TableRow<Person> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
Person rowData = row.getItem();
System.out.println(rowData);
}
});
return row;
});
TableView.setRowFactory((行)->{
TableRow行=新TableRow();
row.setOnMouseClicked(事件->{
如果(event.getClickCount()==2&&(!row.isEmpty()){
Person rowData=row.getItem();
System.out.println(rowData);
}
});
返回行;
});
但是这不能一起工作(我假设是因为我分配了两个相互重写的工厂)。有人能帮我把两个代码示例合并成一个工作的吗?如何在工厂中重写函数(updateItem)并同时附加一个侦听器
致以最诚挚的问候只需将侦听器添加到您在第一个代码块中创建的
表格行
:
TableView.setRowFactory((tv) -> {
TableRow<Row> row = new TableRow<Person>() {
@Override
public void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
switch (person.getPersonStatus()) {
case ST:
setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
case CD:
setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
}
}
};
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
Person rowData = row.getItem();
System.out.println(rowData);
}
});
return row;
});
TableView.setRowFactory((电视)->{
TableRow行=新建TableRow(){
@凌驾
public void updateItem(Person,布尔值为空){
super.updateItem(person,空);
开关(person.getPersonStatus()){
案例ST:
setStyle(“-fx控件内部背景:“+StatusColor.B_LIGHT.getMyColorValue()+”;-fx文本填充:#fff;”);
打破
案例CD:
setStyle(“-fx控件内部背景:“+StatusColor.D_LIGHT.getMyColorValue()+”;-fx文本填充:#fff;”);
打破
}
}
};
row.setOnMouseClicked(事件->{
如果(event.getClickCount()==2&&(!row.isEmpty()){
Person rowData=row.getItem();
System.out.println(rowData);
}
});
返回行;
});
感谢您的快速回答!