How can I externally update a JavaFX scene?

后端 未结 3 899
悲&欢浪女
悲&欢浪女 2021-01-15 13:24

I am trying to learn JavaFX and convert a swing application to JavaFX. What I want to do is use JavaFX to display the progress of a program.

What I was previously do

3条回答
  •  孤街浪徒
    2021-01-15 13:38

    This code does what I think you're looking to do:

    package javafxtest;
    
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.embed.swing.JFXPanel;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    /**
     * @author ericjbruno
     */
    public class ShowJFXWindow {
        {
            // Clever way to init JavaFX once
            JFXPanel fxPanel = new JFXPanel();
        }
    
        public static void main(String[] args) {
            ShowJFXWindow dfx = new ShowJFXWindow();
            dfx.showWindow();
        }
    
        public void showWindow() {
            // JavaFX stuff needs to be done on JavaFX thread
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    openJFXWindow();
                }
            });
        }
    
        public void openJFXWindow() {
            Button btn = new Button();
            btn.setText("Say 'Hello World'");
            btn.setOnAction(new EventHandler() {
    
                @Override
                public void handle(ActionEvent event) {
                    System.out.println("Hello World!");
                }
            });
    
            StackPane root = new StackPane();
            root.getChildren().add(btn);
    
            Scene scene = new Scene(root, 300, 250);
            Stage stage = new Stage();
            stage.setTitle("Hello World!");
            stage.setScene(scene);
            stage.show();
        }
    }
    

提交回复
热议问题