0

I need to use a thread to update data on chart in my application continuously from controller class. The below code is the code of my controller class which is the readData method which is invoked by clicking the button in the GUI and the another method is the run method which update the chart.

    @FXML
    private LineChart<Number, Number> lineChart;


    @FXML
    void readData() {
        Thread t = new Thread (new MainController());
        t.start();
    }


    @Override
    public void run() {
        XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
        while(true) {
            series.getData().add(new XYChart.Data<Number, Number> (10,20));
            series.getData().add(new XYChart.Data<Number, Number> (20,40));
            series.getData().add(new XYChart.Data<Number, Number> (30,10));
            series.getData().add(new XYChart.Data<Number, Number> (40,60));
            lineChart.getData().add(series);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

I got this error (Exception in thread "Thread-5" java.lang.NullPointerException ) on this line of code lineChart.getData().add(series);

  • 1
    whatever you do, you __must not__ update nodes (nor any of their properties) that are in an active scenegraph off the fx application thread - work through a tutorial on concurrency in javafx to learn how to use threading, when stuck come back with a [mcve] demonstrating what's going wrong – kleopatra Oct 23 '20 at 13:01
  • It looks like you have `Controller extends/implements Thread`. This is probably not a good idea. Look [here](https://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm). – SedJ601 Oct 23 '20 at 14:07
  • @kleopatra thank you – Abdulla Elsayed Oct 23 '20 at 15:10
  • 1
    @Sedrick very helpful thank you – Abdulla Elsayed Oct 23 '20 at 15:10

0 Answers0