显示我的网格后无法使线程休眠

时间:2019-05-15 18:09:40

标签: java eclipse events javafx

我有一个想要显示的网格窗格。然后,我想暂停程序2秒钟,并使网格再次不可见。由于某种原因,在我在程序中使用thread.sleep之后,网格变得可见。

这一切都发生在按钮单击事件内。

我尝试绕过thread.sleep,将它们置于新方法中并使用多次睡眠,但没有任何效果。

gameGrid.setVisible(true) 
gameGrid.setVisible(false) 

按钮事件:

public void handleButtonGo(ActionEvent Event) throws IOException {    //On go button press

        boolean validation = true;
        try {

            gameGrid.setVisible(true);
            placeShips();        

        }catch (Exception e){

            labelwarning.setText(e.getMessage());   //on error the program will stop trying to place ships and refresh any ships placed so far.
            validation = false;
            //gameGrid.getChildren().clear();
            //BoardSetup();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            gameGrid.setVisible(false);

        }
}

线程在睡眠后一毫秒内显示网格。

1 个答案:

答案 0 :(得分:1)

使用PauseTransition

public void handleButtonGo(ActionEvent Event) throws IOException {    //On go button press

        boolean validation = true;
        try {

            gameGrid.setVisible(true);
            placeShips();        

        }catch (Exception e){

            labelwarning.setText(e.getMessage());   //on error the program will stop trying to place ships and refresh any ships placed so far.
            validation = false;
            //gameGrid.getChildren().clear();
            //BoardSetup();
            PauseTransition wait = new PauseTransition(Duration.seconds(2));
            wait.setOnFinished((e) -> {
                /*YOUR METHOD*/      
                gameGrid.setVisible(false);
            });
            wait.play();        

        }
}