Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javafx task/thread does not start

I have a JavaFX Program, where I want to import a file and read everything out of this file (should be a .txt) and write it into a String, so I can work on it. Because the files are big sometimes and leave my program saying "No response" and stuff like that, I wanted to add a ProgressBar, to show the current Progress and stop the program from crashing.

At first, I just added a ProgressBar to a Dialog, that opens and updates per binding. But the GUI didn't update, so I found out I have to do a new Thread, that runs in the background, so my program doesn't stop responding. So I packed everything into a Task and started the task with a Thread, but now the Dialog with the ProgressBar doesn't even show up, so I debugged it and found out that the program doesn't even do the task, it just like, goes over it without doing anything.

Here is my current code, I hope anyone can help me with my problem or explain Tasks/Threads to me:

MyHandler:

package application.handler;

import application.data.KTChat;
import application.gui.MyRootPane;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class MyHandler implements EventHandler<ActionEvent> {
    private MyRootPane mp;
    private FileChooser fc;
    private Stage primaryStage;
    private KTChat kt;

    public MyHandler(MyRootPane mp, Stage primaryStage) {
        this.mp = mp;
        fc = new FileChooser();
        fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text files (*.txt)", "*.txt"));
        this.primaryStage = primaryStage;
        kt = new KTChat(mp);
    }

    @Override
    public void handle(ActionEvent event) {
            String mdata = ((MenuItem)(event.getSource())).getId();
            if(mdata.equalsIgnoreCase("import")) {
                kr.readFile(fc.showOpenDialog(primaryStage));
            }
    }
    public KTChat getKT() {
        return kt;
    }
}

MyRootPane (my GUI):

package application.gui;

import java.io.File;

import application.handler.MyHandler;
import javafx.beans.property.DoubleProperty;
import javafx.collections.ObservableList;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MyRootPane extends BorderPane {
    private TextArea eingabe = new TextArea();
    private TextArea ausgabe = new TextArea();
    private MenuBar mb = new MenuBar();
    private Menu m2 = new Menu("Settings");
    private MenuItem mi4 = new MenuItem("Import chat");
    private Stage primaryStage;
    private MyHandler mh;
    private FortschrittDialog fd = new FortschrittDialog();

    public MyRootPane(Stage primaryStage) {
        this.primaryStage = primaryStage;
        mh = new MyHandler(this, primaryStage);
        initSettings();
        setTop(mb);
        setCenter(eingabe);
        setBottom(ausgabe);
    }
    public void initSettings() {
        ausgabe.setEditable(false);
        eingabe.setPrefHeight(500);
        ausgabe.setPrefHeight(500);

        mi4.setId("import");
        mi4.setOnAction(mh);
        m2.getItems().add(mi4);
        mb.getMenus().add(m2);
    }
    public void eingabeSetText(String eingabe) {
        this.eingabe.setText(eingabe);
    }
    public String eingabeGetText() {
        return eingabe.getText();
    }
    public void startFortschrittDialog() {
        fd.show();
    }
    public void endFortschrittDialog() {
        fd.close();
    }
    public void isFortschrittDialogCompleted() {
        if(fd.isCompleted()) endFortschrittDialog();
    }
    public DoubleProperty progressP() {
        return fd.getPBProgressProperty();
    }
}

Then my KTChat where the String should have been build originally:

package application.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import application.gui.MyRootPane;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableDoubleValue;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;

public class KTChat {

    private String chat;

    private MyRootPane mp;

    public KTChat(MyRootPane mp) {
        this.mp = mp;
    }
    public void setChat(String eingabeGetText) {
        this.chat = eingabeGetText;
        getChat();
    }
    public void readFile(File chat) {
        Task<Void> task = new Task<Void>() {

            @Override
            protected Void call() throws Exception {
                if(chat.getName().contains("KakaoTalk_")) {
                    mp.startFortschrittDialog();
                    mp.setFortschritt(-1.0f);
                    String s = "";
                    String gesamt = "";
                    double laenge = 0;
                    try(BufferedReader brCount = new BufferedReader(new FileReader(chat))) {
                        while((s=brCount.readLine())!=null) {
                            laenge++;
                        }
                    } catch (IOException e) {
                        System.out.println("Fehler beim zählen");
                    }
                    double momentanErreicht = 0;
                    try(BufferedReader br = new BufferedReader(new FileReader(chat))) {
                        while((s=br.readLine())!=null) {
                            momentanErreicht++;
                            updateProgress(momentanErreicht, laenge);
                            s = s.replace("ß", "ß");
                            s = s.replace("ö", "ö");
                            s = s.replace("ü", "ü");
                            s = s.replace("ä", "ä");
                            s = s.replace("Ä", "Ä");
                            s = s.replace("Ãœ", "Ü");
                            s = s.replace("Ö", "Ö");
                            gesamt += s+"\n";
                        }
                    } catch (FileNotFoundException e1) {
                        System.out.println("File not found");
                    } catch (IOException e2) {
                        System.out.println("IOException");
                    }
                    mp.isFortschrittDialogCompleted();
                    mp.eingabeSetText(gesamt);
                    setChat(mp.eingabeGetText());
                    getChat();
                } else mp.mhNichtPassendesFile();
                return null;
            }
        };
        mp.progressP().bind(task.progressProperty());
        Thread th = new Thread(task);
        th.setDaemon(true);
        th.start();
    }

The Dialog where my ProgressBar is:

package application.gui;

import javafx.beans.property.DoubleProperty;
import javafx.scene.control.Dialog;
import javafx.scene.control.ProgressBar;

@SuppressWarnings("rawtypes")
public class FortschrittDialog extends Dialog {

    private ProgressBar pb = new ProgressBar();

    public FortschrittDialog() {
        pb.setPrefWidth(500);
        pb.setProgress(-1f);

        getDialogPane().setContent(pb);
    }
    public DoubleProperty getPBProgressProperty() {
        return pb.progressProperty();
    }
    public boolean isCompleted() {
        if(pb.getProgress()==1.0) return true;
        else return false;
    }
}

And last but not least the Main class:

package application;

import application.gui.MyRootPane;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            MyRootPane root = new MyRootPane(primaryStage);
            Scene scene = new Scene(root,1280,720);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setTitle("KT-Chat-Statistics V1.1");
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I tried to include everything that is relevant for the problem, you should be able to just Copy Paste the code to test it for yourself. I really don't understand why it is not working.

like image 428
Korlimann Avatar asked Jul 12 '17 22:07

Korlimann


1 Answers

I found the problem. For everyone else who is experiencing the same problem or just wants to know, here is what I did wrong:

You can't call JavaFX-Thread-Methods during your background task, so every method that reaches outside the Task (I think only the mp.-methods) will not be executed. Therefore, the ProgressBar in the Dialog I made will function, but the Dialog will just not be shown, because the method to show the Dialog lays in the MyRootPane-Class. And as we now know, JavaFX-Thread-Methods can not be executed during the background task.

So, here is what exactly changed in the code, so it can function: You have to put all mp.-methods outside the task, so before you start the task through the thread, just open the dialog there, like:

        mp.progressP().bind(task.progressProperty());
        mp.startFortschrittDialog();
        Thread th = new Thread(task);
        th.setDaemon(true);
        th.start();

I hope this is clear and easy to understand, thank you all for your time.

like image 185
Korlimann Avatar answered Nov 02 '22 06:11

Korlimann