Simple Swing Delay

守給你的承諾、 提交于 2019-11-28 14:30:20

If your code modifying your Swing component's state is on the EDT here (it should be), then no repainting of the label with the first text will take place even if you do call repaint(), because all other EDT requests queued before the last repaint need to complete before you reach that repaint, and your code here is one of those queued EDT events.

If you call repaint, it adds a repaint to the queue, it doesn't repaint right away. Your actions here will result in a 5 second wait, with the label before the next repaint having only the text you last set it to (as code queued on the EDT is executed fully before going to what next is queued).

Try using a Swing Timer, events fired from the Swing Timer are already executing on the EDT, so it's pretty much what you need, one event here where you set the text initially, and another event fired by the Swing Timer to change the text after 5 seconds.

Edit, example of Swing Timer firing once, after 5 seconds as requested by author:

    // set first jlabel text here

    ActionListener task = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("This is on the EDT after 5 seconds, " +
                "well depending on if I'm used with a Timer, and if " +
                "the right options are set to that Timer");
            // set second jlabel text here
        }
        };
    Timer timer = new Timer(5000 , task);
    timer.setRepeats(false);
    timer.start();

I have a popup jDialog which pops up with a jlabel that says "Hang on 5 seconds."

You have a dialog that is visible BEFORE:

  1. you set the text on the label
  2. the Thread.sleep()

The code following popupDialog.setVisible(true) is not executed until the dialog is closed. Reorder your code.

Also, you need to use a Swing Timer to schedule the changing of the text.

       popUpLabel.setVisible(true);
       popUpLabel.setText("Working, hang on a sec....");

should be

       popUpLabel.setText("Working, hang on a sec....");
       popUpLabel.setVisible(true);

and AFTER this you should set the dialog to visible.

You could also keep the order of your code as you have it now - and force the label / panel to update. Though this seems like less of a logical choice in this scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!