【问题标题】:JavaFX, Changing Pie Chart slices' name cause IllegalStateExceptionJavaFX,更改饼图切片的名称导致 IllegalStateException
【发布时间】:2014-10-15 10:05:27
【问题描述】:

我现在正在使用一个 JavaFX,现在我创建了 PieChart 我在教程中看到“http://docs.oracle.com/javafx/2/charts/pie-chart.htm#CIHFDADD” 饼图标签可能有用,因此我让它显示名称和数据值 像这样

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);

结果和最初的一样好 下一步是根据用户选择的数据使其动态化

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

pieChartData.get(index).setName(caption[index]+"\n"+(int)(percent*100)+"%"); 的原因

线程“AWT-EventQueue-0”中的异常 java.lang.IllegalStateException:不在 FX 应用程序线程上; currentThread = AWT-EventQueue-0

无论如何要更改切片名称?或使结果类似于我上面描述的?

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    Exception 中可以看出最可能的原因是方法setSlice() 是从JavaFX Application Thread 以外的线程调用的。

    有很多方法可以解决这个问题:

    1. 这个最简单,调用JavaFX Application thread中的方法
    2. 可以从Application Thread调用方法,或者覆盖Platform.runLater()里面的方法体

    你可以这样做:

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

    或者,

    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. 您还可以查看Concurrency in JavaFX 以了解如何使用TaskService

    【讨论】:

    • 由于这似乎是一个集成了 JavaFX 和 Swing/AWT 的应用程序,this tutorial 也可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多