Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

java - Redirect Console Output to JavaFX TextArea?

I want to show the console output in a JavaFX TextArea... unfortunately I cannot find any working example for JavaFX but only for Java Swing, which not seems to work in my case.

EDIT:

I tried to follow this example: http://unserializableone.blogspot.ch/2009/01/redirecting-systemout-and-systemerr-to.html

and extended my code as shown below. However, there is no console output anymore in my Eclipse IDE but also no output in my TextArea. Any idea where I am doing wrong?

public class Activity extends OutputStream implements Initializable {

@FXML
public static TextArea taRecentActivity;

public Activity() {
    // TODO Auto-generated constructor stub
}

@Override
public void initialize(URL location, ResourceBundle resources) {

    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
}

private void updateTextArea(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            taRecentActivity.appendText(text);
        }
    });
}

@Override
public void write(int arg0) throws IOException {
    // TODO Auto-generated method stub

}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just did this and it worked. Though it was very slow with large amounts of text.

public void appendText(String str) {
    Platform.runLater(() -> textField.appendText(str));
}

and

@Override
public void initialize(URL location, ResourceBundle resources) {
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            appendText(String.valueOf((char) b));
        }
    };
    System.setOut(new PrintStream(out, true));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...