JavaFX Thread - Error on specific component (Label)

64 Views Asked by At

I have a strange error happening. Consider the code bellow and this AtualizadorVeiculos.getInstance().atualizaBanco() method.

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

Notice that I pass a listener as second parameter; this is called by another JavaFx thread inside the method, many times, when some event occur. When it is called I update 3 GUI components: the lblPercentual (Label), tblCarregados (Table), and the pgBar (Progressbar).

The strange thing is that both the table and the progress bar update correctly, but not the label! If I remove its line, things work perfectly. To make it stranger, the exception only runs when the whole processing is finished and the progress bar is full.

I'm lost.

The atualizaBanco method.

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

The error:

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

There are 0 best solutions below