首页 > 解决方案 > 如何返回自定义类型从视图(GUI)到控制器?

问题描述

我正在为一个 42 项目制作一个名为 Swingy 的 MVC 游戏,它需要我在 MVC 模式中实现一个控制台和一个 GUI 视图。我想我会有一个我的视图实例(控制器内的 GUI 或控制台)。所以我创建了一个名为 Viewable 的接口,两个视图都可以实现。问题是我的控制器调用 this.view.newHero() 应该返回一个新的 Hero() 对象,但我不知道如何从 GUI 获取返回值。

我试过使用 ArrayBlockingQueue 但问题似乎源于我界面中的返回值。

控制器

public GameController() {
    this.view = new GUI(); // Just for testing, will either be new Console or new GUI
    this.hero = this.view.newHero(); // The problematic function
    this.makeNewBoard();
    this.gameBoard.printBoard();
}

界面

public interface Viewable {
  public Hero newHero();
}

控制台查看 newHero 方法(缩短)

public Hero newHero() {
  name = getInput();
  heroClass = getInput();
  return new Hero(name, heroClass);
}

图形用户界面

public Hero newHero() {
  //Here I've tried making a blockingQueue and waiting for input but the issue is that my function must return a Hero type. If I return null then it causes an issue in the controller.
}

在 GUI 视图中,用户单击按钮开始新游戏,然后应打开 JOptionPane 输入对话框并询问英雄名称。然后它应该返回一个具有此名称的新英雄。

标签: javaswingmodel-view-controllerblockingqueueeventqueue

解决方案


推荐阅读