Skip to content

Commit f13c8b8

Browse files
committed
Added JavaFX Task
1 parent a1ba0ba commit f13c8b8

3 files changed

Lines changed: 42 additions & 3 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.genuinecoder.javafxtask;
2+
3+
import javafx.concurrent.Task;
4+
5+
public class CounterTask extends Task<Long> {
6+
7+
private final long limit;
8+
9+
public CounterTask(long limit) {
10+
this.limit = limit;
11+
}
12+
13+
@Override
14+
protected Long call() throws Exception {
15+
long sum = 0;
16+
for (int i = 0; i < limit; i++) {
17+
sum = sum + i;
18+
updateValue(sum);
19+
updateProgress(i, limit);
20+
updateMessage("Done upto: " + i);
21+
}
22+
return sum;
23+
}
24+
}

JavaFX Task/src/main/java/com/genuinecoder/javafxtask/HelloController.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,24 @@ public void initialize(URL location, ResourceBundle resources) {
2525

2626
@FXML
2727
public void handleButtonStartAction(ActionEvent actionEvent) {
28-
calculate();
28+
invokeCounterTask();
2929
}
3030

31-
private void calculate() {
31+
private void invokeCounterTask() {
32+
String inputString = textFieldInput.getText();
33+
inputString = inputString.replaceAll(",", "");
34+
long input = Long.parseLong(inputString);
35+
36+
CounterTask counterTask = new CounterTask(input);
37+
counterTask.valueProperty().addListener((observable, oldValue, newValue) -> labelDisplay.setText(String.valueOf(newValue)));
38+
progressBar.progressProperty().bind(counterTask.progressProperty());
39+
40+
Thread th = new Thread(counterTask);
41+
th.setDaemon(true);
42+
th.start();
43+
}
44+
45+
private void calculateInGuiThread() {
3246
String inputString = textFieldInput.getText();
3347
inputString = inputString.replaceAll(",", "");
3448
long input = Long.parseLong(inputString);

JavaFX Task/src/main/resources/com/genuinecoder/javafxtask/hello-view.fxml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<?import javafx.scene.layout.*?>
66
<?import javafx.scene.text.*?>
77

8-
<VBox alignment="TOP_CENTER" prefWidth="440.0" spacing="20.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.genuinecoder.javafxtask.HelloController">
8+
<VBox alignment="TOP_CENTER" prefWidth="500.0" spacing="20.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.genuinecoder.javafxtask.HelloController">
99
<children>
1010
<VBox alignment="TOP_CENTER">
1111
<children>
@@ -32,5 +32,6 @@
3232
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
3333
</VBox.margin>
3434
</VBox>
35+
<ProgressBar fx:id="progressBar" maxWidth="1.7976931348623157E308" minHeight="25.0" progress="0.0" />
3536
</children>
3637
</VBox>

0 commit comments

Comments
 (0)