在控制器中调用视图方法 [英] Calling view method in controller

查看:111
本文介绍了在控制器中调用视图方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在控制器中调用视图方法,但我不知道如何:)我寻求的例子,但我没有找到它。我可以在这段代码中执行此操作吗?我是否必须重新建造它?
我使用javafx和fxml技术(构建用户界面)。

I want invoke view method in controller but I don't know how :) I sought like example, but I don't found it. Can I do that in this code ? whether I must build it anew ? I use javafx and fxml technology( to build user interface ).

我的视图文件(它有gotoRegister()和gotoLogin()方法(我想要调用它们))

My view file ( it have gotoRegister() and gotoLogin() method ( i want to invoke them ))

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()方法)

My controller ( here i want invoke gotoRegister() method )

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文件的其他方式(来自控制器)?

My question: Can I invoke gotoRegister ? or, maybe is other way to change fxml file ( from controller )?

推荐答案

将此代码放入FXMLExampleMVC.java

put this code in FXMLExampleMVC.java

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

现在你可以像这样在控制器中调用你的视图方法

and now you can call your view methods in controller like this

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

这篇关于在控制器中调用视图方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆