JavaFX auto-scroll auto-update text

后端 未结 1 672
小蘑菇
小蘑菇 2021-01-19 06:54

Newbie question about JavaFX that I haven\'t been able to answer, despite knowing it must be pretty simple to do and not finding any resources on it anywhere I\'ve looked (t

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 07:19

    1. To log strings you can use TextArea
    2. To make it asynchronious you need to make a separate thread for output reader.

    public class DoTextAreaLog extends Application {
    
        TextArea log = new TextArea();
        Process p;
    
        @Override
        public void start(Stage stage) {
            try {
                ProcessBuilder pb = new ProcessBuilder("ping", "stackoverflow.com", "-n", "100");
    
                p = pb.start();
    
                // this thread will read from process without blocking an application
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //try-with-resources from jdk7, change it back if you use older jdk
                            try (BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                                String line;
    
                                while ((line = bri.readLine()) != null) {
                                    log(line);
                                }
                            }
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }).start();
    
                stage.setScene(new Scene(new Group(log), 400, 300));
                stage.show();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    
        }
    
        @Override
        public void stop() throws Exception {
            super.stop();
            // this called on fx app close, you may call it in user action handler
            if (p!=null ) {
                p.destroy();
            }
        }
    
        private void log(final String st) {
            // we can access fx objects only from fx thread
            // so we need to wrap log access into Platform#runLater
            Platform.runLater(new Runnable() {
    
                @Override
                public void run() {
                    log.setText(st + "\n" + log.getText());
                }
            });
        }
    
        public static void main(String[] args) {
            launch();
        }
    }
    

    0 讨论(0)
提交回复
热议问题