javafx - 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();
}
}
}
解决方案
这段代码:
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
循环之外。
推荐阅读
- regex - 检查表达式的第二部分是第一部分的增量
- sql - 为每个类别的 N 行设置行号
- c - 位切片:找到最小值
- itext7 - 为什么我无法在 iText7 中更改二维码的大小?
- typescript - 更新到 typescript 3.8,使数组只读
- laravel - Laravel Eloquent Accessor 没有在关系中工作?
- c# - Facebook 在 ASP.Net Core Identity 中登录移动 API 并使用 Facebook 应用程序登录
- geolocation - 点附近道路功能类检索不准确
- spring-boot - 如何解决h2数据库和springboot中错误的用户名和密码错误?
- vue.js - Vue 中的动态根 url 结构,带有 vue-router、路由保护和 Vuex