Calling view method in controller

2019-02-19 19:32发布

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 ).

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);  
    }
}

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
      //
    }
}

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

1条回答
劫难
2楼-- · 2019-02-19 20:00

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();
    }
查看更多
登录 后发表回答