在控制器调用视图方法(Calling view method in controller)

2019-07-17 15:02发布

我想调用在控制器视图的方法,但我不知道我怎么:)喜欢寻求的例子,但我没有发现它。 我可以这样做,在该代码? 我是否必须重新构建它? 我使用JavaFX和FXML技术(构建用户界面)。

我的观点文件(它有gotoRegister()和gotoLogin()方法(我想调用它们))

public class FXMLExampleMVC extends Application{

    protected Parent root;
    @Override
    public void start(Stage stage) throws Exception {
        gotoLogin();

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.setTitle("JavaFX Welcome!");
        scene.getStylesheets().add(FXMLExampleMVC.class.getResource("cssforapp.css").toExternalForm());

        stage.show();
    }

    public void gotoRegister() throws IOException{
        root = FXMLLoader.load(getClass().getResource("RegisterFXML.fxml"));  
    }
    public void gotoLogin() throws IOException{
        root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
    }

    public static void main(String[] args) {
      launch(args);  
    }
}

我的控制器(在这里我要调用gotoRegister()方法)

public class SampleController {

    public SampleModel model = new SampleModel();
    @FXML
    protected Text actiontarget;
    @FXML
    protected PasswordField passwordField;
    @FXML
    protected TextField loginField;

    @FXML protected void handleSubmitButtonAction(){
        if((loginField.getText().equals(model.returnLogin()))&&(passwordField.getText().equals(model.returnPass())) ){
            actiontarget.setText("You have access !");
        } else {
           actiontarget.setText("Wrong data !"); 
        }

    }
    @FXML protected void handleSubmitButtonRegister() throws IOException{
        // 
       //Here I want to invoke gotoRegister
      //
    }
}

我的问题:我可以调用gotoRegister? 或者,也许是其他的方式来改变FXML文件(从控制器)?

Answer 1:

放在FXMLExampleMVC.java验证码

private static FXMLExampleMVC instance;
public FXMLExampleMVC() {
           instance = this;
}
// static method to get instance of view
public static FXMLExampleMVC getInstance() {
        return instance;
}

现在你可以打电话给你的观点方法控制这样的

  @FXML protected void handleSubmitButtonRegister() throws IOException{
        // 
       //Here I want to invoke gotoRegister
        FXMLExampleMVC.getInstance().gotoRegister();
    }


文章来源: Calling view method in controller