【问题标题】:Using Thread.sleep to get waiting effect in JavaFX [duplicate]在JavaFX中使用Thread.sleep获得等待效果[重复]
【发布时间】:2018-07-13 20:52:11
【问题描述】:

我想实现这样的事情:用户按下登录按钮,然后标签显示: “连接。”
0.5 秒时间间隔
“正在连接..”
0.5 秒时间间隔
“正在连接……”
等等

只是一种视觉效果,表明某事实际上正在“幕后”进行。

我设法得到的并不是我所期望的。我单击按钮,等待 1.5 秒,然后我得到“正在连接...”,缺少前面的 2 个步骤。

首先,我的Status

public class Status {
    private static StringProperty status = new SimpleStringProperty();

    public static void setStatus(String newStatus) {
        status.setValue(newStatus);
    }

    public static String getStatus() {
        return status.getValue();
    }

    public static StringProperty get() {
        return status;
    }
}

还有我的LoginView 班级

public class LoginView extends Application {

   private Button loginButton = new Button("Log in");
   private Label statusLabel;

   private void createLabels() {        
      statusLabel = new Label(Status.getStatus());
      statusLabel.textProperty().bind(Status.get());
   }

}  

 private void createButtons() {        
        loginButton.setOnAction(e -> {
            try {
                Status.setStatus("Connecting.");
                Thread.sleep(500);
                Status.setStatus("Connecting..");
                Thread.sleep(500);
                Status.setStatus("Connecting...");
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        });
    }

【问题讨论】:

标签: multithreading javafx


【解决方案1】:

您应该使用Timeline API 制作动画。看看这里:

https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html

基本上,您只需在 0.5 秒的距离处定义 KeyFrames 并设置文本的值以添加另一个点。您也可以让它无限重复直到建立连接以获得循环动画。

另一种方法是创建一个SequentialTransition,它将有两个PauseTransitions,时间为0.5 秒。

顺便说一句,在您的代码中,您暂停了主 UI 线程,这就是您看不到动画的原因。

【讨论】:

    【解决方案2】:

    从不同的线程运行TaskTask 允许您更新它在 JavaFX 应用程序线程上的 message 属性,该属性应该用于更新 GUI,并且不能被长时间运行的任务阻塞,因为它负责渲染:

    Task<Void> task = new Task<Void>() {
    
        @Override
        protected Void call() throws InterruptedException {
            updateMessage("Connecting.");
            Thread.sleep(500);
            updateMessage("Connecting..");
            Thread.sleep(500);
            updateMessage("Connecting...");
            Thread.sleep(500);
    
            return null;
        }
    
    };
    
    // bind status to task's message
    Status.get().bind(task.messageProperty());
    
    // run task on different thread
    new Thread(task).start();
    

    【讨论】:

      猜你喜欢
      • 2012-11-05
      • 2019-11-25
      • 2022-01-01
      • 2013-03-20
      • 2014-08-19
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      相关资源
      最近更新 更多