我正在尝试使用JavaFX中的LineChart
创建距离-时间图表,但是遇到了困难。 x轴很简单,我想显示时间被分成相等的间隔。
y轴比较棘手,因为我需要不规则间隔的刻度线,这些刻度线代表旅程中的各个点,即除了显示一个轴在0到100英里之间划分之外,我还需要标出各种离散点,例如起点是0英里,下一个是1.3英里,下一个是2.7英里,下一个是4.7,依此类推。
这是我的FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="576.0" prefWidth="952.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="timing.com.graphingapp.ui.GUIController">
<children>
<LineChart fx:id="lineGraph" layoutX="321.0" layoutY="35.0" prefHeight="533.0" prefWidth="548.0" title="Test Graph">
<xAxis>
<NumberAxis side="BOTTOM" fx:id="xAxis" />
</xAxis>
<yAxis>
<NumberAxis fx:id="yAxis" side="LEFT" />
</yAxis>
</LineChart>
</children>
</AnchorPane>
这是控制器
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package timing.com.graphingapp.ui;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.Axis.TickMark;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.TableRow;
/**
* FXML Controller class
*
* @author user
*/
public class GUIController implements Initializable {
@FXML
private LineChart<Double, Double> lineGraph;
@FXML
private NumberAxis yAxis;
private final XYChart.Series<Double, Double> series;
public GUIController() {
this.series = new XYChart.Series<>();
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
for(int i = 0; i < 9; i++) {
double position = Math.random() * 10;
XYChart.Data data = new XYChart.Data();
data.setXValue(i);
data.setYValue(position);
series.getData().add(data);
TickMark<Number> tm = new TickMark<>();
tm.setLabel("" + position);
tm.setPosition(position);
yAxis.getTickMarks().add(tm);
}
lineGraph.getData().add(series);
}
}
这样做会产生以下结果:
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at timing.com.graphingapp.ui.GUIController.initialize(GUIController.java:70)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 12 more
在此行...
yAxis.getTickMarks().add(tm);
细读Axis.getTickMarks()
的代码表明,返回了TickMark<T>
对象的不可修改列表,这似乎是症结所在。
有什么方法可以在y轴上的离散点上标记刻度线?