Mo Patchara
Mo Patchara

Reputation: 13

JavaFX, Changing Pie Chart slices' name cause IllegalStateException

I am now work one JavaFX and now I create PieChart I saw in tutorial "http://docs.oracle.com/javafx/2/charts/pie-chart.htm#CIHFDADD" that the pie chart label might be useful, thus I let it show the name and data value as this

private String[] caption = {dataInp.getConstantValue(15, 8)+"\n"+(int)(percent[0]*100)+"%"
        , dataInp.getConstantValue(16, 8)+"\n"+(int)(percent[1]*100)+"%"
        , dataInp.getConstantValue(17, 8)+"\n"+(int)(percent[2]*100)+"%"
        , dataInp.getConstantValue(18, 8)+"\n"+(int)(percent[3]*100)+"%"};
pieChartData = FXCollections.observableArrayList(
            new PieChart.Data(caption[0], percent[0]),
            new PieChart.Data(caption[1], percent[1]),
            new PieChart.Data(caption[2], percent[2]),
            new PieChart.Data(caption[3], percent[3]));
chart = new PieChart(pieChartData);

the result is perfectly fine as the initial the next step is make it dynamic following the data user select by

public void setSlice(double percent, int index){
        pieChartData.get(index).setPieValue(percent);
        pieChartData.get(index).setName(caption[index]+"\n"+(int)(percent*100)+"%");
    }

and the line pieChartData.get(index).setName(caption[index]+"\n"+(int)(percent*100)+"%"); cause

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = AWT-EventQueue-0

Is there anyway to change the slice name? or make the result similar to what I describe above?

Upvotes: 0

Views: 577

Answers (1)

ItachiUchiha
ItachiUchiha

Reputation: 36742

The most probable reason that can be seen from the Exception is that the method setSlice() is called from a thread other than JavaFX Application Thread.

There are many ways to resolve this issue:

  1. This is the easiest one, call the method from the JavaFX Application thread
  2. You can call the method from the Application Thread, or cover the method body inside Platform.runLater()

You can do something like:

Platform.runLater(new Runnable(){
     setSlice(10, 3);
});

or,

public void setSlice(double percent, int index){
   Platform.runLater(new Runnable(){
       pieChartData.get(index).setPieValue(percent);
       pieChartData.get(index).setName(caption[index]+"\n"+(int)(percent*100)+"%");
   });
}
  1. You can also look into Concurrency in JavaFX to have some knowledge on how to use Task and Service classes

Upvotes: 0

Related Questions