我想创建一个扩展JFXPanel以处理折线图的类,并将此JFXPanel与我在Java SE中创建的应用程序集成,我还可以从我的JFrame应用程序实时将数据传递给图形。
这是我的示例代码:
public class LineChartJFXPanel extends JFXPanel {
private final LineChart<Number,Number> chart;
private final HashMap<String, XYChart.Series<Number,Number>> series;
private final NumberAxis xAxis, yAxis;
public LineChartJFXPanel() {
Platform.setImplicitExit(false);
series = new HashMap<>();
xAxis = new NumberAxis(0.0,10.0,1.0);
yAxis = new NumberAxis(0.0,10.0,1.0);
chart = new LineChart<>(xAxis,yAxis);
setScene(new Scene(chart));
}
public void setSeries(String idSeries, String nameSeries, Number xIni, Number yIni){
XYChart.Series<Number,Number> newSeries = new XYChart.Series<>();
newSeries.setName(nameSeries);
newSeries.getData().add(new XYChart.Data<>(xIni,yIni));
chart.getData().add(newSeries);
series.put(idSeries, newSeries);
}
}
******************************************
public class PanelChart extends JPanel{
LineChartJFXPanel lineChart;
public PanelChart(){
setLayout(new GridLayout(1, 2));
lineChart = new LineChartJFXPanel();
add(lineChart);
}
}
********************************
public class Main extends JFrame{
PanelChart chartPanel;
public Main(){
setPreferredSize(new Dimension(800, 600));
chartPanel = new PanelChart();
getContentPane().add(chartPanel);
setVisible(true);
}
public static void main(String args[]){
Main main = new Main();
main.setVisible(true);
}
}
但是当我运行代码时,它会显示以下错误:
Exception in thread "main" java.lang.IllegalStateException: Not on FX application thread; currentThread = main
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:237)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:400)
at javafx.scene.Scene.<init>(Scene.java:290)
at javafx.scene.Scene.<init>(Scene.java:198)
at javachartdemo.LineChartJFXPanel.<init>(LineChartJFXPanel.java:39)
at javachartdemo.PanelChart.<init>(PanelChart.java:22)
at javachartdemo.Main.<init>(Main.java:21)
at javachartdemo.Main.main(Main.java:27)
我的申请需要更改什么?
答案 0 :(得分:2)
错误消息告诉您必须在FX应用程序线程中运行触及JavaFX的所有内容,因为JavaFX不是线程安全的。
要在该线程上执行某些操作,请使用Platform.runLater
请注意,Swing有一个类似的限制,区别在于没有任何东西会抛出异常。相反,你迟早会得到奇怪的行为。对于SwingUtilities.invokeLater
答案 1 :(得分:0)
需要在JavaFX应用程序线程上发生Scene对象和调用JFXPanel.setScene,如下所示:
Platform.runLater(() -> {
setScene(new Scene(chart));
});