java 5 秒后从 JLabel 中删除文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14668151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:01:44  来源:igfitidea点击:

Delete Text from JLabel after 5 seconds?

javaswingjlabel

提问by Pablo Stein

I wanted to know if there's any easy way to delete the content (text) from a JLabel after 5 seconds. Is that possible? Because I have a JLabel in a JFrame and it shows some internal errors from the program I'm coding and I want the JLabel to show the message for a couple of seconds and then go to blank. Any ideas?

我想知道是否有任何简单的方法可以在 5 秒后从 JLabel 中删除内容(文本)。那可能吗?因为我在 JFrame 中有一个 JLabel,它显示了我正在编码的程序的一些内部错误,我希望 JLabel 显示消息几秒钟,然后变为空白。有任何想法吗?

回答by Guillaume Polet

Simplest solution is to use a Swing Timer. It will prevent freezing the GUI and ensure proper Thread access (ie, UI modification is performed on the EDT).

最简单的解决方案是使用 Swing Timer。它将防止冻结 GUI 并确保正确的线程访问(即,在 EDT 上执行 UI 修改)。

Small demo example:

小演示示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLabelDelete {
    private JFrame frame;
    private JLabel label;

    protected void initUI() {
        frame = new JFrame(TestLabelDelete.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel("Some text to delete in 5 seconds");
        frame.add(label);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        Timer t = new Timer(5000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(null);
            }
        });
        t.setRepeats(false);
        t.start();
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestLabelDelete testLogin = new TestLabelDelete();
                testLogin.initUI();
            }

        });
    }

}

回答by Micha? Ziober

Use Timer. Please see my example.

使用定时器。请看我的例子。

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class SourceCodeProgram {

    private static void createAndShowGUI() {
        // Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        // Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setMinimumSize(new Dimension(200, 300));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Add the ubiquitous "Hello World" label.
        final JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        // Display the window.
        frame.pack();
        frame.setVisible(true);

        Timer timer = new Timer(5000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // Clear text or whatever you want
                label.setText("New text");
            }
        });
        // start Tick-Tack
        timer.start();
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Or you can write a separate class, which can clean label.

或者你可以写一个单独的类,它可以清理标签。

class JLabelCleaner {

    private JLabel label;
    private int waitSeconds;

    public JLabelCleaner(int waitSeconds, JLabel label) {
        this.label = label;
        this.waitSeconds = waitSeconds;
    }

    public void startCountdownFromNow() {
        Timer timer = new Timer(waitSeconds * 1000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText("");
            }
        });
        timer.start();
    }
}

Now, you can use it whenever you need it in this way:

现在,您可以随时以这种方式使用它:

new JLabelCleaner(5, label).startCountdownFromNow();

Also see:

另见:

回答by Trevor Jex

There is an easy solution to this.

对此有一个简单的解决方案。

JLabel label = new JLabel("error text");
Thread.sleep(5000);
label.setText("");

JLabel label = new JLabel("error text");
Thread.sleep(5000);
label.setText("");

Hope this helps!

希望这可以帮助!

EDIT: If you don't want the program to freeze for 5 secs you'll have to put this inside a Runnable.

编辑:如果您不希望程序冻结 5 秒,则必须将其放入 Runnable 中。

回答by Upendra Siripurapu

It's very easy to do... just create a new thread and write code to clear text on label, and make that thread to sleep for 5sec and then start it.

这很容易做到……只需创建一个新线程并编写代码以清除标签上的文本,并使该线程休眠 5 秒,然后启动它。

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class LabelThread {
    private JLabel textLabel;

    public LabelThread() {
        try {
            JFrame frame  = new JFrame("Label");
            frame.setSize(500, 500);

            textLabel = new JLabel("Hiiii.... Kill me");
            frame.setContentPane(textLabel);

            frame.setVisible(true);

            MyThread thread = new MyThread();
            MyThread.sleep(5000);
            thread.start();
        } catch (InterruptedException ex) {

        }
    }
    class MyThread extends Thread{

        @Override
        public void run() {
            System.out.print("Running thread");
            textLabel.setText("");
        }

}
public static void main(String args[]){
    LabelThread labelThread = new LabelThread();
}
}