Task /progress bar JavaFX application

2019-08-26 02:41发布

问题:

In my javaFx app I'm trying to attach my progress bar to a task which is supposed to execute some methods from another class, I cannot seem to get the task to run through these methods when i click the button for this task.

This is my search page controller for two words inputted by user

FXML Controller class

public class WordComparePageController implements Initializable  {
@FXML
private TextField wordOneText;
@FXML
private TextField wordTwoText;
@FXML
private Button pairSearchButton;
@FXML
private TextField wordPairText;

WordNetMeasures wordNetMeasures = new WordNetMeasures();

private double distance;
private double linDistance;
private double leskDistance;

DecimalFormat df = new DecimalFormat("#.0000");
DecimalFormat pf = new DecimalFormat("#.0");
@FXML
private ProgressBar progressBar;
@FXML
private ProgressIndicator progressIndicator;

@Override
public void initialize(URL url, ResourceBundle rb) {}

Binds progress bar too task

@FXML
private void onSearchButtonClicked(ActionEvent event) throws    InstantiationException, IllegalAccessException {

   progressBar.progressProperty().bind(taskPS.progressProperty());
       progressIndicator.progressProperty().bind(taskPS.progressProperty());

    Thread th = new Thread(taskPS);
    th.setDaemon(true);
    th.start();
            }

  Task<Void> taskPS = new Task<Void>() {

    @Override
    protected Void call() throws InstantiationException, IllegalAccessException {
       updateProgress(0, 1);

        distance = wordNetMeasures.searchForWord(wordOneText.getText(), wordTwoText.getText());
        linDistance = wordNetMeasures.linMethod(wordOneText.getText(), wordTwoText.getText());
        leskDistance =   wordNetMeasures.leskMethod(wordOneText.getText(), wordTwoText.getText());
       updateProgress(1, 40);
        ProjectProperties.getInstance().setPathResult(distance);

        System.out.println("Distance: = " + ProjectProperties.getInstance().getPathResult());

    ProjectProperties.getInstance().setWordText(wordOneText.getText() + "," + wordTwoText.getText());

        String wordNetDistance = String.valueOf(df.format(distance));
        ProjectProperties.getInstance().setPathWordNetText(wordNetDistance);
        ProjectProperties.getInstance().setLinWordNetText((String.valueOf(df.format(linDistance))));
        ProjectProperties.getInstance().setLinResult(linDistance);
        ProjectProperties.getInstance().setPathResult(distance);
        ProjectProperties.getInstance().setLeskResult(leskDistance);
            ProjectProperties.getInstance().setLeskWordNetText((String.valueOf(df.forma  t(leskDistance))));

        updateProgress(40, 70);



        Database databaseConnection = new Database();
        try {
            databaseConnection.getConnection();
             databaseConnection.addWordNetToDatabase(ProjectProperties.getInstance().getWordText(), distance, linDistance, leskDistance);
            updateProgress(100, 100);
        } catch (SQLException ex) {
            Logger.getLogger(WordComparePageController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
};

}

Class with the wordnet measure methods for the task

public class WordNetMeasures {


private static ILexicalDatabase db = new NictWordNet();
private static RelatednessCalculator[] rcs = {
    new HirstStOnge(db), new LeacockChodorow(db), new Lesk(db), new WuPalmer(db),
    new Resnik(db), new JiangConrath(db), new Lin(db), new Path(db)
};

private static RelatednessCalculator pathMethod = new Path(db);
private static RelatednessCalculator linMethod = new Lin(db);
private static RelatednessCalculator leskMethod = new Resnik(db);
private static double distance;
private static double linDistance;
private static double leskDistance;



public static double searchForWord(String word1, String word2) {
    WS4JConfiguration.getInstance().setMFS(true);
    RelatednessCalculator rc = pathMethod;
    distance  = rc.calcRelatednessOfWords(word1, word2);

    return distance;
}


public static double linMethod(String word1, String word2) {
    WS4JConfiguration.getInstance().setMFS(true);
    RelatednessCalculator rc = linMethod;
    linDistance = rc.calcRelatednessOfWords(word1, word2);

    return linDistance;
}


public  static double leskMethod(String word1, String word2) {
    WS4JConfiguration.getInstance().setMFS(true);
    RelatednessCalculator rc = leskMethod;
    leskDistance = rc.calcRelatednessOfWords(word1, word2);

    return leskDistance;
}


/**
 * Gets the ontology path for the word passed in
 * @param word
 * @return
 * @throws JWNLException 
 */
public String[] getWordNetPath(String word) throws JWNLException {

    String[] wordResults = new String[500];
    RiWordnet wordnet = new RiWordnet();
    String[] posOfWord = wordnet.getPos(word);
    int[] wordIds = wordnet.getSenseIds(word, posOfWord[0]);
    wordResults = wordnet.getHypernymTree(wordIds[0]);

    return wordResults;
}

/**
 * Gets the set of synsets for the word passed in
 * @param word
 * @return 
 */
public String[] getWordNetSynset(String word) {
    RiWordnet wordnet = new RiWordnet();
    String[] posOfWord = wordnet.getPos(word);
    int[] wordIds = wordnet.getSenseIds(word, posOfWord[0]);
    String[] wordResults = wordnet.getSynset(wordIds[0]);

    return wordResults;
}

}

回答1:

A Task is meant to be used only once. To reuse it, you have to reinstantiate it, or create a class which extends Service.

Service takes care of creating and managing the Task and has the benefit of not having to reattach the binding for the progressProperty.

The ProgressBar has to be added to a Scene to be visible

public class TestApp extends Application {

    private Stage progressStage;

    @Override
    public void start(Stage primaryStage) throws IOException {

        Button btn = new Button("start task");

        TaskService service = new TaskService();
        service.setOnScheduled(e -> progressStage.show());
        service.setOnSucceeded(e -> progressStage.hide());

        ProgressBar progressBar = new ProgressBar();
        progressBar.progressProperty().bind(service.progressProperty());

        progressStage = new Stage();
        progressStage.setScene(new Scene(new StackPane(progressBar), 300, 300));
        progressStage.setAlwaysOnTop(true);

        btn.setOnAction(e -> service.restart());

        primaryStage.setScene(new Scene(new StackPane(btn), 300, 300));
        primaryStage.show();
    }

    private class TaskService extends Service<Void> {

        @Override
        protected Task<Void> createTask() {
            Task<Void> task = new Task<Void>() {

                @Override
                protected Void call() throws Exception {

                    for (int p = 0; p < 100; p++) {
                        Thread.sleep(40);
                        updateProgress(p, 100);
                    }
                    return null;
                }
            };
            return task;
        }
    }

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


标签: javafx task