我们正在创建一款Dominion纸牌游戏。
游戏使用MVC,客户端服务器和Java序列化进行通信。
下面发布的代码片段显示了用于从服务器读取消息的客户端类:
public class ReadMsgFromServer implements Runnable {
ObjectInputStream in;
ServiceLocatorClient sl = ServiceLocatorClient.getServiceLocator();
ChatMessageLobby msg;
Client_Model model;
Client_View_playingStage view_playingStage;
public ReadMsgFromServer (ObjectInputStream in, Client_Model model){
this.in = in;
this.model=model;
}
@Override
public void run() {
GameObject obj;
try {
while ((obj = (GameObject) this.in.readObject()) !=null){
switch (obj.getType()) {
case ChatMessageLobby:
ChatMessageLobby msg = (ChatMessageLobby) obj;
String name = msg.getName();
String text = msg.getMsg();
sl.getTextAreaLobby().appendText(name+": "+text+"\n");
sl.getTextAreaLobby().selectPositionCaret(sl.getTextAreaLobby().getText().length());
break;
case InformationObject:
break;
case GameParty:
GameParty newGame = (GameParty) obj;
Platform.runLater(new Runnable() {
@Override
public void run() {
sl.addNewGame(newGame);
}
});
break;
//updating the ListView of this client when he logs in (he needs to see all open games when he enters the lobby)
case UpdateLobby:
UpdateLobby toUpdate = (UpdateLobby) obj;
Iterator<GameParty> iter = toUpdate.getListOfOpenGames().iterator();
Platform.runLater(new Runnable() {
@Override
public void run() {
while (iter.hasNext()){
sl.addNewGame(iter.next());
}
}
});
break;
case UpdateGameParty:
UpdateGameParty newUpdate = (UpdateGameParty) obj;
Platform.runLater(new Runnable() {
@Override
public void run() {
sl.updateGameParty(newUpdate.getGameParty());
}
});
break;
case JoinGameParty:
JoinGameParty join=(JoinGameParty) obj;
GameParty gamePartyToJoin=join.getSelectedGameParty();
Platform.runLater(new Runnable() {
@Override
public void run() {
Stage playingStage = new Stage();
playingStage.initModality(Modality.APPLICATION_MODAL);
view_playingStage = new Client_View_playingStage (playingStage, model,false);
new Client_Controller_playingStage(model, view_playingStage,gamePartyToJoin);
view_playingStage.start();
}
});
break;
case CancelGame:
Platform.runLater(new Runnable() {
@Override
public void run() {
view_playingStage.stop();
}
});
default:
}
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
每个客户都可以在大厅创建一个新游戏。其他客户可以加入此游戏。
如果客户加入游戏,则在客户端,他会阅读GameObject
类型JoinGameParty
switch
案例编号6)。
在那里,他的视图playingStage
将在新的Runnable
中在JavaFX线程上创建。
对于这个视图,我已经创建了实例变量"Client_View_playingStage view_playingStage;"
,它将在前面提到的switch
情况下进行初始化。视图开始没有问题。
现在我要实现以下功能:
stage.hide();
),我已经实现了switch
案例编号7(CancelGame
)。view_playingStage
案例编号6(switch
)中初始化的实例变量JoinGameParty
。view_playingStage.stop();
行上,run
方法中,它会在JavaFX线程上产生NullPointerException
。 为什么会发生这种情况?我已经初始化了实例变量view_playingStage
。 或者我是否被迫在这里与房产(ObjectProperty
等)合作?