JavaFX LineChart作为TreeTableView中的单元格

时间:2015-07-01 01:43:12

标签: java javafx javafx-8

首先,我熟悉Java和Swing,但我是FX新手,并且在FX8工作。

我正在尝试将JavaFX LineChart作为TreeTableView中的单元格。我已经收集到我需要使用setCellFactory on the column来显示图表,我正在定义TreeTableCell的自定义版本,如下所示

public class SparklineCell<T> extends TreeTableCell<T,Series> {

  private LineChart getEmptyLineChart() {
    final NumberAxis xAxis = new NumberAxis();
    final NumberAxis yAxis = new NumberAxis();
    final LineChart xyChart = new LineChart<>(xAxis, yAxis);
    // configure the chart and axes...
    return xyChart;
  } 

  @Override
  protected void updateItem(Series item, boolean empty) {
    super.updateItem(item, empty);

    if (!empty && item!=null) {
        LineChart chart = getEmptyLineChart();
        chart.getData().setAll(item);
        Platform.runLater( () -> {
            setGraphic(chart);
            setText(null);
        });
    } else {
        Platform.runLater( () -> {
            setGraphic(null);
            setText(null);
        });
    }

  }
}

请注意,每次运行updateItem时,我都会在添加数据之前实例化一个新的LineChart并完全配置它。我知道这是一个糟糕的形式,但我已经尝试将它作为SparklineCell类的成员并且每次重复使用它(在线查看的图像视图中有很多示例...请参阅上面的链接以获取使用ProgressBar的示例) ,它会遇到问题,其中图表显示为空,或移动到不同的单元格,或者两组数据出现在单个图表上,或者抛出异常以向图表添加重复系列等。

这显然正在发生,因为SparklineCell实例正在整个表中被重用,但我该怎么办呢?更具体地说,以下代码不起作用,如何在每次重绘单元格时不创建全新图表的情况下修复它?

public class SparklineCell<T> extends TreeTableCell<T,Series> {

  final NumberAxis xAxis = new NumberAxis();
  final NumberAxis yAxis = new NumberAxis();
  final LineChart xyChart = new LineChart<>(xAxis, yAxis);

  public SparklineCell() {
    //configure the chart and axes...
  } 

  @Override
  protected void updateItem(Series item, boolean empty) {
    super.updateItem(item, empty);

    if (!empty && item!=null) {
        xyChart.getData().setAll(item);
        Platform.runLater( () -> {
            setGraphic(xyChart);
            setText(null);
        });
    } else {
        Platform.runLater( () -> {
            setGraphic(null);
            setText(null);
        });
    }

  }
}

0 个答案:

没有答案
相关问题