简体   繁体   中英

MVC, Swing and exception in Java

I'm developing a game in Java and I'm using the MVC Design Pattern and swing for the GUI. Model, view and controller communicate between them with observer/observable design pattern. Now in the controller and in the view I must throw exception when a player wants to do an illegal action in the game. For example, if the player wants to buy anything in the game but he has 0 coins, in the view will throw an exception. There is a way to show a JDialog when an exception is throw to show to the player that he can't do that action? Can the view catch the exception of the controller and of the view?

Maybe I misunderstood your question I don't get why you throw the exception in the view. doesn't make sense to me. but

// the model ///////////////////

class player{

int coin count = 0

setcoincount(int number){ // }

getcoincount() { // }
}

// the controller ///////////////////

class cont{

model m;
view v;

cont(model m, view v){
// code..
}

int checkBalance(){

return m.getBalance(); 
// get the balance from the model
// sends it to the view
}

}

// the view ///////////////////

class view{

cont c;

// when the player click the buy button
..... butonClick event handle.. (){

c.checkBalance(); 
// if the balance is 0 throw an exception

}

}

// the main method ///////////////////

class mian{

 psvm(string args[]){

// the model and view doesn't know each other

model m = new model()

view v = new view()

controller c = new controller (m , v )

v.setVisible true


}    
}

Consider using Actions (as part of the controller).

  • Actions can be triggered by view events, and can modify the model.
  • Actions can have precoditions , which determine if they are enabled . This allows you to check, for example, if the player has enough coins to buy an item.
  • You can bind the action directly to a 'buy' button (action's enabled state determines whether the button is enabled, and pressing the button executes the action).
  • Actions can throw Exceptions, for all problems that can't be handled by preconditions (user may have enough coins, but the connection to the gaming server is lost, preventing the purchase).

I recommend using a framework-agnostic action interface, and creating adapters (here: for Swing) where necessary.

public interface Action {

    public void execute () throws Exception;

    public boolean isEnabled ();
}

For actions who can be bound to UI elements (buttons, menu, ...):

public interface DisplayableAction extends Action {

    public String getName();

    public String getTooltip();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM