【问题标题】:Calling view method in controller在控制器中调用视图方法
【发布时间】:2012-12-27 19:12:48
【问题描述】:

我想在控制器中调用视图方法,但我不知道如何:) 我寻找类似的例子,但我没有找到它。我可以在这段代码中这样做吗?我是否必须重新建造它? 我使用 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 文件(来自控制器)?

【问题讨论】:

  • 注:设置字段 root 不会改变场景的内容(现在是 Java 作品)。您需要致电scene.setRoot(root) 来实现这一点。所以更好的选择是将scene 存储为一个字段,并使用新的根直接调用setRoot() 方法。
  • 谢谢,我会使用你的解决方案:)

标签: java javafx-2 fxml


【解决方案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();
    }

【讨论】:

  • 当 gotoRegister() 方法的返回类型不是 void 时,它不起作用。你能解释一下吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多