猿问

如何让 JavaFX 在运行下一行代码之前等待节点完成配置

我必须执行一个复杂的过程来加载需要不同时间的图像,并且在此过程运行时,我想通知用户一个进程实际上正在后台运行。

为此,我已经放弃了一些动画,因为它实际上必须在不同线程的背景中,所以我想要的只是一个大红色文本,上面写着“正在加载......请稍候”。

简化示例:

主要:


public class Controller {

    @FXML

    StackPane mainPane;


    Text text;


    public void initialize(){

        text = new Text();

        text.setText("please wait");

        text.setVisible(false);

        mainPane.getChildren().add(text);


    }


    public void handleMouseClick(){

        text.setVisible(true);

        longProcess();

        text.setVisible(false);

    }


    public void longProcess(){

        try {

            Thread.sleep(10000);

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

Fxml 文件:


<?import javafx.scene.layout.StackPane?>

<StackPane fx:controller="sample.Controller"

           xmlns:fx="http://javafx.com/fxml"

           fx:id="mainPane"

           onMouseClicked="#handleMouseClick">

</StackPane>

因此,这段代码创建了一个简单的堆栈窗格并向其中添加了一个不可见的文本,然后在鼠标单击时它应该首先显示文本然后使线程休眠(类似于我的漫长过程)然后使文本再次不可见但它只是使线程休眠和由于某种原因不显示文本。


郎朗坤
浏览 137回答 2
2回答

米脂

将您的 handleMouseClickMethod 更改为如下所示,它应该可以工作public void handleMouseClick(){&nbsp; &nbsp; int delayTime = 10;//Set this to whatever you want your delay in Seconds&nbsp; &nbsp; Label text = new Label("please wait");&nbsp; &nbsp; mainPane.getChildren().add(text);&nbsp; &nbsp; final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();&nbsp; &nbsp; executorService.scheduleAtFixedRate(()->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Platform.runLater(()->mainPane.getChildren().remove(text)), delayTime, 1, TimeUnit.SECONDS);}

慕田峪9158850

编辑:由于 kleopatra 指出旧代码段不起作用,我已经搜索了如何做到这一点并找到了这个答案:“以下代码将暂停并更改标签中的值(完全公开,我正在重用我为另一个问题编写的代码):”https://stackoverflow.com/a/26454506/10971694老的:下面的代码会有帮助吗?while(!node.isVisible()){&nbsp; &nbsp;System.out.println("waiting...");&nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp; &nbsp;Thread.sleep(delay);&nbsp; &nbsp;} catch (InterruptedException e) {&nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();&nbsp; &nbsp;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答