Java FXML,更改标签文本,暂停 GUI x 秒,然后再次更改标签文本

问题描述 投票:0回答:1

我目前正在制作一款神奇宝贝同人游戏,但我遇到了一个问题(不是最后一个)。

所以事情是这样的,因为这是一轮又一轮的游戏,我必须这样做:

  • 决定哪只神奇宝贝先攻击。
  • 更改 GUI 上的标签文本以告知用户正在发生的情况。
  • 等待x秒。
  • 然后其他神奇宝贝攻击。
  • 更改 GUI 上的标签文本以告知用户正在发生的情况。
  • 等待x秒。

所有这些都工作得很好,除了等待 x 秒部分,第一个标签更改直接被跳过。

这是我的代码的简单版本:

public class BattleController implements Initializable {
    @FXML
    private Label lblInfoBattle;
    
    private boolean firstAttack;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //things when the scene appear on the screen
    }
    
    //Calling this method when clicking on an attack
    public void btnAttackClicked() {
        //Here I decide who attack first and other things...
        
        String myCustomText = ("The first pokemon attack");
        firstAttack = true;

        //Then I'm calling this method I created
        waitForSeconds(myCustomText);

        //Then the other Pokémon attack and many things... 

        myCustomText = ("The second pokemon attack");
        firstAttack = false;

        //Then I'm calling this method I created
        waitForSeconds(myCustomText);
    }

    private void waitForSeconds(String myCustomText){
       //Here I want to put the pause function;

       //Here is my currently solution
       if (firstAttack) {
            lblInfoBattle.setText(myCustomText);
        } else {
            PauseTransition pt = new PauseTransition(Duration.seconds(2));
            pt.setOnFinished(e -> lblInfoBattle.setText(myCustomText));
            pt.play();
        }
    }
}

我已经尝试过 ->

Thread.sleep
Timer
/
TimerTask
TimeLine
TranslateTransition

我只是在寻找一种简单的方法来创建暂停而不冻结 GUI。

user-interface javafx fxml pause
1个回答
0
投票

社区wiki答案:

楼主在评论里自己解决了问题

他将要执行的代码包含在

setOnFinished()
PauseTransition
中,这是正确的方法。

原评论:

啊,好吧,我明白了,我必须在 setOnFinished PauseTransition 中包含“第二次攻击部分”,是的,这是有道理的。我会尝试一下,谢谢你的帮助^^ – 基利安·格拉斯 7 月 2 日 22:13 发表评论

© www.soinside.com 2019 - 2024. All rights reserved.