我根据CodeReview.SE问题的建议重构我的代码。 https://codereview.stackexchange.com/questions/126634/button-clicking-ui-for-a-game
研究
我知道你必须创建一个方法来调用其他地方。 doSomething代码不能只停留在类级别。
错误:
我遇到了错误
令牌上的语法错误" saveGameOnClose",此令牌后预期的标识符
内
FRAME.addWindowListener(new WindowAdapter() {
SaveGameData.saveGameOnClose();
});
我的主要班级。
主要类别:
public Game() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
NewGameMessage.LoadNewGameMessage();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace(); }
catch (IllegalAccessException ex) {
ex.printStackTrace(); }
catch (InstantiationException ex) {
ex.printStackTrace(); }
catch (ClassNotFoundException ex) {
ex.printStackTrace(); }
FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FRAME.getContentPane().add(new addComponentsToPane());
FRAME.setSize(300, 500);
FRAME.setLocationRelativeTo(null);
FRAME.setVisible(true);
FRAME.setResizable(false);
FRAME.addWindowListener(new WindowAdapter() {
SaveGameData.saveGameOnClose();
});
}
});
}
SaveGameData类:
public class SaveGameData {
// Game.FRAME.addWindowListener(new WindowAdapter() {
static void saveGameOnClose(WindowEvent e) {
BufferedWriter writerOut = null;
try {
writerOut = new BufferedWriter(new FileWriter("res/saved_game_data.txt"));
writerOut.write(String.valueOf(Game.biDamageOutput) + "\r\n" +
String.valueOf(Game.biPoints) + "\r\n" +
String.valueOf(Game.biNewPoints) + "\r\n" +
String.valueOf(Game.biSpentPoints) + "\r\n" +
String.valueOf(Game.biKnifeCount) + "\r\n" +
String.valueOf(Game.biPistolCount) + "\r\n" +
String.valueOf(Game.biShotgunCount) + "\r\n" +
String.valueOf(Game.biRifleCount) + "\r\n" +
String.valueOf(Game.biRLauncherCount) + "\r\n" +
String.valueOf(Game.intTotalClicks));
writerOut.close();
} catch (Exception e1) {
System.err.println("Error: " + e1.getMessage());
}
};
}
个人认为问题:
我错误地编写了Window Listener。但是,我尝试将每个值得注意的操作,加载,保存,UI单独分类,作为学习更多关于类,可持续性,代码重用性的一部分。或者我可能会错过一个支架或支架。
感谢。
答案 0 :(得分:1)
您的方法SaveGameData.saveGameOnClose(WindowEvent e)
需要WindowEvent
类型的参数,但您在没有任何参数SaveGameData.saveGameOnClose();
的情况下调用它,并且没有实现任何侦听器方法
它应该是这样的
FRAME.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
SaveGameData.saveGameOnClose(e);
}
});