等待按钮被按下JAVA GUI

目前,我正在重新编写一个具有GUI的基于文本的程序。我遇到的问题之一是我希望程序等待直到满足特定条件。用户单击“步行”按钮直到player.walked属性= 5即可满足此条件。当使用基于文本的界面时,这非常简单,请使用while循环,并且内部具有输入功能。

while (player.getWalked() < 5) {
     //wait for user input via terminal through the scanner.
}

但是,当使用GUI并希望遵循Model-View Controller的方法(即,将游戏机制和用户界面内容分开)时,这将变得相当困难。尝试实现GUI后,由于while循环现在为空,因此我的程序保持冻结。我将在下面尝试证明这一点,但这相当令人困惑。如果这不专业,我深表歉意。

世界级:

public static void play(Player player) throws FileNotFoundException, IOException, ClassNotFoundException{ // play method is the centralised place for all in-game simulation and user interaction.
    welcome(player);
    while (player.getWalked() <5) {

    }

GUI类:

Button walk_button = new Button("Walk");
      walk_button.setBounds(195, 395, 100,100);
      add(walk_button);
      walk_button.addActionListener((new ActionListener(){ 
        public void actionPerformed(ActionEvent evt) {
            try{
                label1.setVisible(false);
                label.setText(player.interaction("W"));
                label.setBounds(200,50,400,100);
                }
            catch (FileNotFoundException e) {System.out.println(e.getMessage());} catch (IOException e) {System.out.println(e.getMessage());} catch (ClassNotFoundException e) {System.out.println(e.getMessage());} 
            } 
        }));

Player class consisting of the interaction method:

public String interaction(String input) throws FileNotFoundException, IOException, ClassNotFoundException{ 
//String input = World.input("You have walked "+getWalked()+" miles so far.\nOnly "+(END_POINT - walked)+" miles until you reach the end of the town.\nPress 'w' to walk.\nPress 'c' to change weapon equipped.\nPress 's' to save and exit.");
if (input.equals("W")) {
   return walk(World.dice(4,1));
}

如果有人能找到解决方案,我将不胜感激。最终目标是使程序继续运行(允许播放器继续按“步行”按钮),直到while循环中断为止。

如果时间太长,令人困惑且不专业,非常感谢您。

评论
  • wnatus
    wnatus 回复

    It's not a great idea to have empty while loops, so I would suggest checking the player's position with an if-statement in the same method where it is set (right after the button trigger actionPerformed), and then continuing from there. I can't give you a specific implementation though because I don't know what you want to do.

    Side note: Instead of having multiple catch blocks where you do the same thing, just use FileNotFoundException | ClassNotFoundException | etc.