java SWT中Label实时刷新当前时间

同样最近在开发swt的一个项目,业务中的一个功能模块类似百度网盘的上传进度条

0/80。

即已上传0个,总共80个。效果展示要的就是实时刷新,2/80呀,15/80呀,针对这个,就有了这篇文章。

下面附上【Label实时刷新时间】参考代码和原文链接,我是看这段代码加上这篇文章有的灵感。

public class test01
{
    private static Shell shell;

    public static void main(String[] args) {
        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }


    protected static void createContents() {
        shell = new Shell();
        shell.setSize(450, 300);
        shell.setText("实时刷新时间");

        final Label label = new Label(shell, SWT.NONE);
        label.setFont(SWTResourceManager.getFont("微软雅黑", 13, SWT.NORMAL));
        label.setBounds(69, 48, 174, 41);
        new Thread() {//线程操作
            public void run()
            {
                while(true)
                {
                    try
                    {
                        //对Label进行实时刷新,需要加上这句
                        label.getDisplay().asyncExec(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                // 设置时间 ,格式化输出时间
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String s = sdf.format(new Date());
                                label.setText(s);//输出到Label上
                            }
                        });
                        Thread.sleep(1000);//每隔一秒刷新一次
                    }
                    catch (Exception e)
                    {
                    }

                }
            }
        }.start();
    }
}

原文地址:https://www.cnblogs.com/qq1445496485/p/14875069.html