java - MVC 和图形组件

标签 java model-view-controller graphics

我试图用 Java 创建一个遵循 MVC 模式的游戏。我的问题是我想不出一个好方法将存储在模型中的游戏 map 传递给 View 中的绘制组件。

我的代码的一个非常简化的版本:

模型

public class Model {    

    //0,0,200,200,0.... are read from a file and stored in a List 
    //inside the model.     
    private List<Integer> gameMap;   

    public Model(){
        gameMap = new ArrayList<Integer>(); 

    }

看法
public class View extends JFrame{
    private class GameBoard extends JComponent{                 
        public void paintComponent(Graphics g){

            //Now I need the values from the List in the Model to my 
            //View for the g.drawRect methods

            g.drawRect(0, 0, 200, 200);                 
        }
    }

Controller
public class Controller {

    public Controller(View view, Model model) {

    }

最简单的方法当然是在 View 中有一个静态列表并执行 Model.gameMap ……但这会破坏 MVC 模式。

如果我通过在 Controller 中执行类似操作在 View 中保留游戏 map 的副本,它仍然是 MVC 吗?
view.gameMap = model.gameMap;   

最佳答案

如果你想遵循MVC模式, View 不能引用模型 .
为了不破坏 MVC, Controller (将读取模型)必须向 View 提供该信息。

您的代码确实简化了,但正确的示例(尊重 MVC)是:
模型

public class Model {    
    
    //GameMap info is read from a file and stored in a List 
    //inside the model.     
    private List<Integer> gameMap;   
    
    public Model(){
        gameMap = new ArrayList<Integer>(); 
        //Read file and fill gameMap
    }

    public List<Integer> getGameMap(){
        return gameMap;
    }
}
看法
public class View extends JFrame{

    private Controller controller;

    public View(Controller controller){
        this.controller = controller;
    }

    private class GameBoard extends JComponent{                 
        public void paintComponent(Graphics g){

            //Now I need the values from the List in the Model to my 
            //View for the g.drawRect methods

            List<Integer> gameMapInfo = controller.getGameMap();
            //Perform custom drawing using this object's values
            //g.drawRect()...
        }

    }
Controller
public class Controller {

    private View view;
    private Model model;

    public Controller(View view, Model model) {
        this.view = view;
        this.model = model;
    }

    public List<Integer> getGameMap(){
        return model.getGameMap();
    }
View 保存了 Controller 的引用,当需要绘制时,会向 Controller 询问它需要的信息。 Controller 询问模型,并将信息返回给 View 。

关于java - MVC 和图形组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583470/

相关文章:

java - java JFrame 错误

java - 有没有办法在 JRuby 中为 Java 对象获得良好的 `#inspect` 输出?

java - 如何使用 Netbeans IDE 8.0 为 Web 应用程序创建 jar 文件

java - 在 Eclipse 中为 Android 应用程序发布签名 jar

java - SSL 使用对称还是非对称?

PHP MVC 设计 - 对同一 url/ Controller 的多个操作

ruby-on-rails - 模型、 View 和 Controller 如何连接?

c# - .NET 图形 - 创建具有透明背景的椭圆

c# - 如何从 RGB 颜色创建 WPF 图像?

java - 如何在 Java 中将多个 Map/List/Array 从 API url 传递到 RestController?