JavaFx常用语句(查阅用)

1.controller中获取stage

使用场景:点击按钮跳转至其他页面并关闭本页面

Stage stage = (Stage) mybutton.getScene().getWindow();//mybutton为此页面中任一组件的id名
stage.close();

2.载入.fxml文件

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

3.切换页面

public void changePage(ActionEvent event){
        Stage stage = (Stage) mybutton.getScene().getWindow();

        try {
            Parent root = FXMLLoader.load(getClass().getResource("secondpage.fxml"));//载入新页面
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4.非UI线程调用UI线程对组件进行修改

方法来源:javafx非控制类获取控制类的控制器

场景:有一个线程类A与UI启动类B,线程类A想要修改B的组件则需要获取B的控制器类,从而调用其对应方法

public class BarragePage extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("barragepage.fxml"));
        Scene scene = new Scene(fxmlLoader.load());
        BarragePageController bc = fxmlLoader.getController();//获取控制器

        Thread listenThread = new Thread(new ServerNet(bc));//后台监听线程,将控制器传入,从而在ServerNet类内对页面进行修改
        listenThread.start();

        primaryStage.setScene(scene);
        primaryStage.show();//展示当前页面
    }
}

注:上述代码需要注意顺序,可输出bc值判断是否成功获取控制器,获取失败则得到null

Related post

  1. Emacs配置python环境

    2022-11-07

  2. 网址收藏夹

    2020-07-16

  3. Windows下ARM编程实验

    2020-11-29

  4. Swift Learning Log

    2023-08-31

There are no comment yet.

COMMENT

Take a Coffee Break

Recommend post

  1. 常用工具指令

    2022-09-18

Category list

ABOUT

Welcome to FullStar, a captivating online destination where the realms of software development and personal reflections intertwine.

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Life Logs

  1. 回首

    2023-07-14

Return Top