I am new JFX and I am struggling with this. I am trying to run a simple simulation that has to print output (system.out and system.err) to textarea.
public class ConsoleController {
@FXML
public TextArea consoleLogscreen;
private class Console extends OutputStream {
@Override
public void write(int b) throws IOException {
consoleLogscreen.appendText(String.valueOf((char) b));
}
}
@FXML
public void initialize() throws IOException {
Console console = new Console();
PrintStream ps = new PrintStream(console, true);
System.setOut(ps);
System.setErr(ps);
System.err.flush();
System.out.flush();
}
}
SimulationController:
public class SimulationController {
@FXML
private Button homebutton;
@FXML
private Button abortbutton;
private volatile Service<Void> backgroundThread;
private volatile Thread t;
private volatile Simulate sim;
@FXML
public void initialize() {
sim = new Simulate();
t = new Thread(sim);
backgroundThread = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
t.run();
return null;
}
};
}
};
backgroundThread.setOnCancelled(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
t.interrupt();
sim.shutDown(true);
}
});
backgroundThread.restart();
abortbutton.setDisable(false);
homebutton.setDisable(true);
}
@FXML
void onAbortClicked(ActionEvent event) throws IOException {
if (event.getSource() == abortbutton) {
backgroundThread.cancel();
}
}
@FXML
void onHomeClicked(ActionEvent event) throws IOException {
if (event.getSource() == homebutton) {
Utility.getHome((Stage) homebutton.getScene().getWindow());
}
}
}
Simulation.fxml:
<Pane prefHeight="500.0" prefWidth="750.0"xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.jfxabstract.view.SimulationController">
<children>
<Button fx:id="abortbutton" alignment="CENTER" contentDisplay="CENTER" layoutX="250.0" layoutY="430.0" mnemonicParsing="false" onAction="#onAbortClicked" styleClass="custombutton" text="Abort" textAlignment="CENTER" />
<Button fx:id="homebutton" alignment="CENTER" contentDisplay="CENTER" layoutX="450.0" layoutY="430.0" mnemonicParsing="false" onAction="#onHomeClicked" styleClass="custombutton" text="Home" textAlignment="CENTER" />
<fx:include source="Console.fxml" />
</children>
</Pane>
I am using javafx.concurrent.service to run my task but the application is freezing and also the printing the output is not in realtime.
Can anyone suggest where I might have gone wrong.
Thanks in advance.
Update:
the run method retrieves data from database and runs few validations by invoking other methods in same class. For simple abstract application I am using this
public void run() {
long i = 1;
while (i < 90) {
double k = Math.sqrt(Math.pow(i, 2) / Math.sqrt(i));
System.out.println("i: " + i + " Count: " + k);
if (!shutdown) {
break;
}
i++;
}
}