1

我的 tableView 中有这个自定义的 CellFactory。滚动时,该列异常缓慢。为什么会这样,我该如何改进它。

lastTradeColumn.setCellFactory(
   new Callback<TableColumn<Stock, Price>,TableCell<Stock, Price>>(){
      @Override public TableCell<Stock, Price> call( TableColumn<Stock, Price> p ) {
         TableCell<Stock, Price> cell = new TableCell<Stock, Price>() {
            @Override public void updateItem(Price price, boolean empty) {
               super.updateItem(price, empty);
               if (price != null) {
                  VBox vbox = new VBox(5);
                  vbox.getChildren().add(new Label("£"+price.toString()));
                  if( price.getOldPrice() > price.getNewPrice()) {
                     vbox.setStyle("-fx-background-color:#EA2A15;");
                  }
                  else if( price.getOldPrice() < price.getNewPrice()) {
                     vbox.setStyle("-fx-background-color:#9CF311;");
                  }
                  setGraphic( vbox );
               }
            }
         };
         return cell;
   }
});
4

1 回答 1

5

你应该开始做的两件事是:

1) 与其调用 setStyle(...),不如调用 getStyleClass().add(...),然后使用外部 CSS 文件定义样式类。在运行时解析 CSS 很慢,应该避免。

2) 重用 VBox 和 Label,而不是每次调用 updateItem 时都重新创建它。通过将 VBox 和 Label 移到 updateItem 方法之外来做到这一点(但将其保留在新的 TableCell<>() 大括号内。

但是....采取 2) 更进一步,我怀疑您需要 VBox 或标签。只需在单元格本身上设置样式类,然后使用 setText(...) 针对单元格设置文本。

——乔纳森

于 2011-12-11T21:13:59.970 回答