如何在Java中为MVC设计模式分离类(KeyListener与JFrame分离)?
我正在用java用MVC设计模式制作一个arkanoid游戏,我不知道如何使控制器类与视图类分离。它应该是足够简单的任务,我希望在控制器类中创建keyListener,同时在视图类中保留所有可视化内容(我可以自己处理模型)。由于某种原因,我找不到该怎么做。现在我有一个视图类,它扩展了JFrame并实现了keylistener如何在Java中为MVC设计模式分离类(KeyListener与JFrame分离)?,java,model-view-controller,design-patterns,keylistener,Java,Model View Controller,Design Patterns,Keylistener,我正在用java用MVC设计模式制作一个arkanoid游戏,我不知道如何使控制器类与视图类分离。它应该是足够简单的任务,我希望在控制器类中创建keyListener,同时在视图类中保留所有可视化内容(我可以自己处理模型)。由于某种原因,我找不到该怎么做。现在我有一个视图类,它扩展了JFrame并实现了keylistener 我更喜欢一个答案,张贴2个小类的代码 在Swing中,视图和控制器基本上是相同的类,例如(视图和控制器)+(模型)。 如果你想要一个干净的分离,你可以看看哪一个是Swing
我更喜欢一个答案,张贴2个小类的代码 在Swing中,
视图
和控制器
基本上是相同的类,例如(视图和控制器)+(模型)。如果你想要一个干净的分离,你可以看看哪一个是Swing的数据绑定框架,但我不确定它是否是游戏的最佳解决方案。
当然,您可以实现自己的
逻辑层
,例如
public interface GameStateListener {
public void playerPositionChanged(Player p, Position oldPos, Position newPos);
}
// Stores the current state of the game
public class DefaultGameState implements IGameState {
public void addGameStateListener(GameStateListener) {...}
}
// Contains the logic of the game
public class DefaultGameLogic implements IGameLogic {
public DefaultGameLogic(IGameState gameState) {...}
public void doSomething(...) { /* update game state */ }
...
}
// displays information of the game state and translates Swing's UI
// events into method calls of the game logic
public class MyFrame extends JFrame implements GameStateListener {
private JButton btnDoSomething;
public MyFrame(IGameLogic gameLogic, IGameState gameState) {
// Add ourself to the listener list to get notified about changes in
// the game state
gameState.addGameStateListener(this);
// Add interaction handler that converts Swing's UI event
// into method invocation of the game logic - which itself
// updates the game state
btnDoSomething.addActionListener(new ActionListener() {
public void actionPerformed() {
gameLogic.doSomething();
}
});
}
// gets invoked when the game state has changed
// (might be by game logic or networking code - if there is a multiplayer ;) )
public void playerPositionChanged(Player p, Position oldPos, Position newPos) {
// update UI
}
}
使用Java的和接口并不是很方便,因为您需要找出观察对象的哪些属性发生了变化。因此,使用自定义回调接口是实现这一点的常用方法