View Javadoc

1   package nl.tudelft.goal.ut2004.visualizer.gui.action;
2   
3   import java.awt.event.ActionEvent;
4   
5   import javax.swing.AbstractAction;
6   import javax.swing.Action;
7   
8   import nl.tudelft.goal.ut2004.visualizer.controller.ServerController;
9   
10  import cz.cuni.amis.pogamut.ut2004.communication.messages.gbcommands.Pause;
11  import cz.cuni.amis.pogamut.ut2004.communication.messages.gbinfomessages.GameInfo;
12  import cz.cuni.amis.pogamut.ut2004.server.IUT2004Server;
13  import cz.cuni.amis.utils.flag.FlagListener;
14  
15  public class PauseResumeAction extends AbstractAction {
16  
17  	public PauseResumeAction() {
18  		putValue(Action.SHORT_DESCRIPTION, "Pause or resume the game");
19  
20  		ServerController controller = ServerController.getInstance();
21  		controller.getServerDefinition().getServerFlag()
22  				.addListener(new FlagListener<IUT2004Server>() {
23  
24  					@Override
25  					public void flagChanged(IUT2004Server changedValue) {
26  						if (changedValue == null) {
27  							setEnabled(false);
28  						} else {
29  							setEnabled(true);
30  							updateStatus();
31  
32  						}
33  					}
34  				});
35  
36  		updateStatus();
37  	}
38  
39  	private void updateStatus() {
40  
41  		ServerController controller = ServerController.getInstance();
42  		IUT2004Server server = controller.getServer();
43  
44  		if (server == null) {
45  			putValue(Action.NAME, "Pause");
46  			setEnabled(false);
47  			return;
48  		}
49  
50  		setEnabled(true);
51  		GameInfo info = server.getWorldView().getSingle(GameInfo.class);
52  
53  		if (info.isGamePaused()) {
54  			putValue(Action.NAME, "Resume");
55  		} else {
56  			putValue(Action.NAME, "Pause");
57  		}
58  	}
59  
60  	@Override
61  	public void actionPerformed(ActionEvent e) {
62  		ServerController controller = ServerController.getInstance();
63  		IUT2004Server server = controller.getServer();
64  
65  		assert server != null;
66  
67  		GameInfo info = server.getWorldView().getSingle(GameInfo.class);
68  
69  		Pause pauseResume;
70  
71  		if (info.isGamePaused()) {
72  			pauseResume = new Pause(false, false);
73  			putValue(Action.NAME, "Pause");
74  		} else {
75  			pauseResume = new Pause(true, true);
76  			putValue(Action.NAME, "Resume");
77  		}
78  
79  		server.getAct().act(pauseResume);
80  	}
81  
82  }