JavaFX线程 - 特定组件(标签)出错

时间:2015-06-12 02:58:19

标签: multithreading javafx label

我发生了一个奇怪的错误。考虑下面的代码和这个AtualizadorVeiculos.getInstance().atualizaBanco()方法。

AtualizadorVeiculos.getInstance().atualizaBanco(file.getPath(), (line, res, lineNumber) -> {
    DadoCarregadoTabela dado = new DadoCarregadoTabela(line, res);
    int percentual = (int)(lineNumber/(double)numberOfLines * 100);
    this.lblPercentual.setText(percentual + "%");
    this.tblCarregados.getItems().add(dado);
    this.pgBar.setProgress(lineNumber/(double)numberOfLines);
});

请注意,我将侦听器作为第二个参数传递;当某些事件发生时,很多时候,这会被方法中的另一个JavaFx线程调用。 当它被调用时,我更新3个GUI组件:lblPercentual(标签),tblCarregados(表)和pgBar(进度条)。

奇怪的是桌子和进度条都正确更新,但不是标签!如果我删除它的线,事情就完美了。为了使它更奇怪,该异常仅在整个处理完成且进度条已满时运行。

我输了。

atualizaBanco方法。

public void atualizaBanco(String filePath, AtualizacaoListener listener) {
    final ScheduledExecutorService scheduler = Executors
            .newScheduledThreadPool(1);
    scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            String line = "";
            int lineNumber = 0;
            try {
                FileReader inputFile = new FileReader(filePath);
                BufferedReader bufferReader = new BufferedReader(inputFile);
                while ((line = bufferReader.readLine()) != null) {
                    lineNumber++;
                    setDados(line);
                    listener.dadoCarregado(line, true, lineNumber);
                }
                dropListeners();
                bufferReader.close();
            } catch (Exception e) {
                System.out.println("Error while reading file line by line:" + e.getMessage());
                listener.dadoCarregado(line, false, lineNumber);
            }
        }
    }, 10, TimeUnit.MILLISECONDS);
}

错误:

Exception in thread "pool-4-thread-1" java.lang.IllegalStateException: Not on FX application thread; currentThread = pool-4-thread-1`

0 个答案:

没有答案