简体   繁体   中英

javafx swing crashes when trying to display chart twice

I'm making a java swing application with javafx charts added to the JFrame . Click a button it shows a chart in a new window. All works fine the first time around, but on closing the chart window and click a button again, it crashes before displaying the next chart window, at the line

fxPanel.setScene(scene);

I think fxPanel or scene need to be reset when closing the chart window the first time, but nothing I've tried has worked so far. Below is my chart plotting class. Any help muchly appreciated.

public class PlotChart extends JFrame implements WindowListener {

    private JFrame chartWindow = new JFrame("Commitment Of Traders");

    public PlotChart(JFXPanel fxPanel) {
        plotChart(fxPanel);
    }

    public void plotChart(JFXPanel fxPanel) {

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        final LineChart<Number,Number> lineChart = new LineChart<Number,Number>(xAxis,yAxis);
        final Scene scene = new Scene(lineChart,800,600);
        xAxis.setLabel("Week");

        lineChart.setTitle("Commitment of Traders");

        //Define a series
        XYChart.Series commercials = new XYChart.Series<>();
        XYChart.Series nonCommercials = new XYChart.Series<>();
        XYChart.Series CLong = new XYChart.Series<>();
        XYChart.Series CShort = new XYChart.Series<>();
        commercials.setName("Dealers");
        nonCommercials.setName("Hedge Funds");

        //Populate series
        for (int i=0;i<ReadCSV.getCommercials().size();i++) {

            commercials.getData().add(new XYChart.Data(i,ReadCSV.getCommercials().get(i)));
            nonCommercials.getData().add(new XYChart.Data(i,ReadCSV.getNonCommercials().get(i)));
        }

        lineChart.getData().add(commercials);
        lineChart.getData().add(nonCommercials);

        fxPanel.setScene(scene); // exception in this line

        chartWindow.add(fxPanel);
        chartWindow.setSize(800, 600);
        chartWindow.setVisible(true);
        chartWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        chartWindow.addWindowListener(new java.awt.event.WindowAdapter() {

            public void windowClosing(java.awt.event.WindowEvent windowEvent) {

                ReadCSV.clearVars();
                System.out.println("window closed");
            }
        });
    }

WindowListener method overrides omitted

I came across this issue as well just now. I managed to get rid of it by creating a new JFXPanel each time and hence setting the scene only once on each instance. It solves the issue, but probably isn't the most elegant way to solve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM