首页 > 解决方案 > LineChart 中没有显示任何内容

问题描述

当我运行代码时,我得到一个没有数据点或线的图表。在 for 循环中,我添加了数据表的每一行,并且每一行都应该是图表中的一行。有人可以解释为什么会这样吗?


public class PartiesApplication extends Application {

    public static void main(String[] args) {
        launch(args);
    }
    
    public void start(Stage stage){
        NumberAxis xAxis = new NumberAxis(1967, 2009, 4);
        NumberAxis yAxis = new NumberAxis();

        // set the titles for the axes
        xAxis.setLabel("Year");
        yAxis.setLabel("Ranking");

        // create the line chart. The values of the chart are given as numbers
        // and it uses the axes we created earlier
        LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
        lineChart.setTitle("Relative support of the parties");
        lineChart.setLegendVisible(true);
                Scene view = new Scene(lineChart, 640, 480);

        
        Scanner reader = new Scanner("partiesdata.tsv");
        
        String firstLine = reader.nextLine();
        String[] years = firstLine.split("\t");
        while(reader.hasNextLine()){
            String line = reader.nextLine();
            String[] partyData = line.split("\t");
            
            XYChart.Series data = new XYChart.Series();
            data.setName(partyData[0]);
            
            for (int i = 1; i < partyData.length; i++) {
                data.getData().add(new XYChart.Data(years[i], Double.valueOf(partyData[i])));
            }
            lineChart.getData().add(data);
            
            stage.setScene(view);
            stage.show();
        }
        
        
    }

}

标签: javafxcharts

解决方案


这段代码:

Scanner reader = new Scanner("partiesdata.tsv");

正在使用其 Javadoc的构造函数说:Scanner

构造一个Scanner生成从指定字符串扫描的值的新值 [强调添加]

换句话说,扫描器使用"partiesdata.tsv"字符串本身作为数据源。这可能不是你真正想要做的。我假设您打算打开一个名为partiesdata.tsv.

如果是资源,那么您将需要使用接受java.io.InputStream. 例如:

String res = "/partiesdata.tsv"; // may not be the correct path for you
try (Scanner scanner = new Scanner(getClass().getResourceAsStream(res))) {
  while (scanner.hasNextLine()) {
    // parse data...
  }
}

如果是文件,那么您将需要使用接受 ajava.io.File或的构造函数之一java.nio.file.Path。例如:

Path file = Path.of("partiesdata.tsv"); // may not be the correct path for you
try (Scanner scanner = new Scanner(file)) {
  while (scanner.hasNextLine()) {
    // parse data...
  }
}

此外,这两个语句:

stage.setScene(view);
stage.show();

应该移到while循环之外。


推荐阅读