简体   繁体   English

您如何在延迟之前更新 JLabel?

[英]How do you update a JLabel before a delay?

When I try to use any kind of delay on my code the program gets delayed but the JLabel that was put before the delay gets updated after the program ends.当我尝试在我的代码上使用任何类型的延迟时,程序会被延迟,但在延迟之前放置的 JLabel 会在程序结束后更新。

I want the program to:我希望该程序:

  • update the JLabel on the GUI更新 GUI 上的 JLabel
  • wait for 5 seconds等待 5 秒
  • update the JLabel again with diferent text用不同的文本再次更新 JLabel
  • wait another 5 seconds再等 5 秒

I have tried with timers, invokelater, invokeandwait, thread.sleep and others.我尝试过使用计时器、invokelater、invokeandwait、thread.sleep 等。

The problems is that the GUI does get delayed at the right spot but the GUI does not update the JLabel ath place where the code is located.问题是 GUI 确实会在正确的位置延迟,但 GUI 不会更新代码所在位置的 JLabel。 The JLabel gets updated after the program ends. JLabel 在程序结束后更新。

I want the user to be able to read the text for 5 seconds then read another text for another 5 seconds in order.我希望用户能够阅读文本 5 秒钟,然后按顺序阅读另一个文本 5 秒钟。 I do not want the program to run the gui pause at a cetain spot then at end just update the JLabel.我不希望程序在某个位置运行 gui 暂停,然后在最后只更新 JLabel。 I want the gui to get updated before the delay.我希望 gui 在延迟之前得到更新。 I do not want the same thing that when I used a timer to happen where I type in a setText for the JLabel before the Timer is typed and then when I run the program the timer works but the JLabel gets updated after the delay(It is not what I want).我不希望在我使用计时器时发生相同的事情,在输入计时器之前为 JLabel 输入 setText,然后当我运行程序时,计时器工作,但 JLabel 在延迟后更新(它是不是我想要的)。

The way to achieve that is either using a Swing Worker , either aa Swing Timer .实现这一目标的方法是使用 Swing WorkerSwing Timer A Swing worker runs a task in background and at the same time it is capable of publishing GUI changes in the Event dispatch thread (the thread where the GUI runs). Swing worker 在后台运行任务,同时它能够在事件调度线程(GUI 运行的线程)中发布 GUI 更改。 A SwingTimer can be considered as a simplified version of a Swing Worker, that only runs a task after some time in the Event Dispatch Thread . SwingTimer可以被认为是 Swing Worker 的简化版本,它只在Event Dispatch Thread 中运行一段时间后才运行任务。 (Consider a worker that sleeps the thread in background, and after the sleep , it runs the task in the Gui thread). (考虑一个在后台sleeps线程的工作线程,在sleep ,它在 Gui 线程中运行任务)。

There are a lot of examples online, like this one and this one .网上有很多例子,比如这个这个

If you do not want to do something in background, a Timer solution sounds "simpler".如果您不想在后台执行某些操作,Timer 解决方案听起来“更简单”。 Take a look at How can I pause/sleep/wait in a java swing app?看看如何在 java swing 应用程序中暂停/睡眠/等待?

An example where it is closer to what you need (with a worker):一个更接近你需要的例子(有一个工人):

public class WorkerExample extends JFrame {
    private static final long serialVersionUID = 6230291564719983347L;
    private JLabel label;

    public WorkerExample() {
        super("");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new FlowLayout());

        SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {

            @Override
            protected Void doInBackground() throws Exception {
                publish("Started....");
                Thread.sleep(1500);
                for (int i = 0; i < 5; i++) {
                    publish("Number of iterations: " + i);
                    //Do something
                    Thread.sleep(3500);
                }
                return null;
            }

            @Override
            protected void process(List<String> chunks) {
                String chunk = chunks.get(0);
                label.setText(chunk);
            }

            @Override
            protected void done() {
                label.setText("Done.");
            }
        };

        JButton button = new JButton("Start");
        button.addActionListener(e -> worker.execute());
        add(button);

        label = new JLabel("Nothing yet.");
        add(label);

        setSize(400, 400);
        setLocationByPlatform(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new WorkerExample().setVisible(true);
        });
    }
}

You can experiment with these in order to understand how a SwingWorker works, but I strongly recommend you to read concurrency in Swing before doing that.您可以对这些进行试验以了解SwingWorker工作原理,但我强烈建议您在执行此操作之前阅读Swing 中的并发性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM