Issue
I am currently working on a JavaFX-program with SceneBuilder which also utilies the commandline of windows. To show the user that the program is doing something I want it to put the console-output into a textarea. So far it only updates after everything is finished, not in real-time, which is my goal.
Here is the code I have so far, where it enters "tree" as a test. "textareaOutput" is the textarea which shows the output:
try {
Process p = Runtime.getRuntime().exec("cmd /C tree");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
textareaOutput.appendText(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
I know of MessageConsole in Swing, but I don't know if something similar exists in JafaFX
Solution
Here is a simple application, which has the functionality of a real-time command-line binding with a text-area.
- Enter command on
input
(tree, time, etc) TextField and hit Enter key - The results will be appended in the
text-area
constantly
Demo
public class CommandLineTextAreaDemo extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
root.setCenter(getContent());
primaryStage.setScene(new Scene(root, 200, 200));
primaryStage.show();
}
private BorderPane getContent() {
TextArea textArea = new TextArea();
TextField input = new TextField();
input.setOnAction(event -> executeTask(textArea, input.getText()));
BorderPane content = new BorderPane();
content.setTop(input);
content.setCenter(textArea);
return content;
}
private void executeTask(TextArea textArea, String command) {
Task<String> commandLineTask = new Task<String>() {
@Override
protected String call() throws Exception {
StringBuilder commandResult = new StringBuilder();
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
commandResult.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return commandResult.toString();
}
};
commandLineTask.setOnSucceeded(event -> textArea.appendText(commandLineTask.getValue()));
new Thread(commandLineTask).start();
}
}
If you want to use TextArea
independently(without using input
TextField), you can do something like this instead.
textArea.setOnKeyReleased(event -> {
if(event.getCode() == KeyCode.ENTER) {
String[] lines = textArea.getText().split("\n");
executeTask(textArea, lines[lines.length - 1]);
}
});
Answered By - Shekhar Rai
Answer Checked By - Terry (JavaFixing Volunteer)