在JavaFX中访问控制器,然后从另一个类执行一个函数

时间:2016-02-13 16:53:52

标签: java javafx

所以当我尝试运行java代码时,我得到了错误

线程中的异常“AWT-EventQueue-0”java.lang.IllegalStateException:不在FX应用程序线程上; currentThread = AWT-EventQueue-0

LoginController.java

public class LoginController {

    public void onSessionLoginAction() {
        //I have some functions here so i just minimize a bit of the code
        loginUser();
    }

    public void loginUser() {
        Init.getInstance().hideWindow("login"); // Error <---
        Init.getInstance().setEnabled(true);    // Error <---
        Init.getInstance().run();               // Success <--
    }
}

Init.java

public abstract class Init extends Application {

    private static Init instance;
    private boolean isEnabled = false;
    private Timer timer;

    public void initialize(Stage stage) {
        instance = this;

        // Login with session if you can :) Success to run this code here
        timer = new Timer(50, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FXMLLoader loader = loginWindow.getFxmlLoader();
            LoginController loginController = loader.<LoginController>getController();
            loginController.onSessionLoginAction(); //This runs the session on LoginController.java
            timer.stop();
            }
        });
        timer.start();
    }

    public void setEnabled(boolean flag) {
        isEnabled = flag;
    }

    public static Init getInstance() {
        return instance;
    }
    public abstract void run();
}

1 个答案:

答案 0 :(得分:1)

中运行代码
Platform.runLater(new Runnable() {
    @Override 
    public void run() {
        loginController.onSessionLoginAction();
    }
});

或使用Timeline代替Timer