我一直试图弄清楚如何在LineChart已经制作之后从LineChart中删除它。我试过用我想要的系列重新创建场景,但那不起作用。我做了一些故障排除,发现该系列实际上已更改并减少为null,但即使系列为空,该行仍然存在。然后,一旦将系列更改为新数字,它会尝试将点连接到不应存在的旧点。如果有人能帮助我,我将非常感激。
public class GraphSection {
NumberAxis xAxis;
NumberAxis yAxis;
LineChart<Number, Number> lineChart;
Scene scene;
XYChart.Series series1, series2, series3, series4;
public GraphSection(){
xAxis = new NumberAxis();
yAxis = new NumberAxis();
lineChart = new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("Test Graph");
lineChart.setCreateSymbols(false);
lineChart.setLegendVisible(false);
series1 = new XYChart.Series();
series2 = new XYChart.Series();
series3 = new XYChart.Series();
series4 = new XYChart.Series();
lineChart.getData().addAll(series1, series2, series3, series4);
scene = new Scene(lineChart,400,300);
}
public Scene getGraph(){
return this.scene;
}
public void addPoints(int n){
if(n == 1){
//Test Points
series1.getData().add(new XYChart.Data(1,50));
series1.getData().add(new XYChart.Data(2,60));
series1.getData().add(new XYChart.Data(3,70));
series1.getData().add(new XYChart.Data(4,80));
series1.getData().add(new XYChart.Data(5,90));
}
else if(n == 2){
//More Test Points
series1.getData().add(new XYChart.Data(1,70));
series1.getData().add(new XYChart.Data(2,80));
series1.getData().add(new XYChart.Data(3,90));
series1.getData().add(new XYChart.Data(4,100));
series1.getData().add(new XYChart.Data(5,110));
}
else if(n == 3){
}
else if(n == 4){
}
}
public void removePoints(int n){
Series s;
LineChart l = this.lineChart;
if(n == 1){
s = this.series1;
s.getData().clear();
l.removeSeriesFromDisplay(s); //This is the method I would guess I need but
//it is "not visible" and thus produces
// an error when I try to compile.
}
else if(n==2){
series2 = this.series2;
}
else if(n==3){
series3 = this.series3;
}
else if(n==4){
series4 = this.series4;
}
}
}
编辑:因此虽然.remove()
将使其从图中删除该行,但它也会抛出IllegalStateException。虽然这很丑,但不会导致程序崩溃,然而,当我将数据点添加回系列时,它将不会绘制新点的图形。因此,一个潜在的解决方案是动态地将一系列添加到LineChart中。如果有人知道如何做到这一点,那可能会解决我的问题。
//Bottom
JFXPanel bottom = new JFXPanel();
final GraphSection gs = new GraphSection();
bottom.setScene(gs.getGraph());
gs.addPoints(1);
//ActionListeners
testButton1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gs.removePoints(1);
System.out.println(gs.series1.getData()); //Used for debugging
}
});
testButton2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gs.addPoints(2);
System.out.println(gs.series1.getData());
}
});
Start with .addPoints(1); This is what happens with just .getData().clear();
答案 0 :(得分:0)
是的,问题实际上是在Swing JFrame中尝试使用JFXPanel。这意味着出现了illegalStateException。通过更改在JavaFX阶段运行的代码,这允许remove()工作,然后您可以使用lineChart.getData()。add(Series);轻松地动态添加新系列。您可以将swing组件与SwingNodes合并,但我的建议是将GUI重新编码为所有JavaFX。