Swing: Enabling Buttons With Delay

冷暖自知 提交于 2019-12-22 20:46:32

问题


private void OptionsActionPerformed(java.awt.event.ActionEvent evt) 
{ 
 // After clicking on button X, I want 4 other buttons to show up
 // in a sequential order

ButtonTrue(); 
} 


public void ButtonTrue() 
{
    Audio_Options.setVisible(true);
    letsSleep();
    Control_Options.setVisible(true);
    letsSleep();
    Display_Options.setVisible(true);
    letsSleep();
    Network_Options.setVisible(true);
}

 public void letsSleep()
{
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
    }
}

I have 4 buttons. I want them to appear in a sequential order such as : Button1 - 10seconds - Button2 - 10 seconds - Button3 - 10seconds - Button 4

Problem: Whenever I call the function "ButtonTrue()", they all appear together after waiting 30 seconds. What can cause this problem to occur?


回答1:


  • don't use Thread.sleep(int) for Swing JComponent, because blocking current EDT

  • you have look at Swing Timer




回答2:


You should use different Threads for this:

javax.swing.Timer timer = new Timer(10000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    //...Update the progress bar...
        Control_Options.setVisible(true);

        timer.stop();

    }    
});
timer.start();

Your buttons have to be final to be in scope for the anonymous ActionListener.




回答3:


I think the problem is that all setVisble invocations are within one thread, which isn't EventDispatchThread. You could try calling:

if(EventQueue.isDispatchThread()) {
    ButtonTrue();
} else {
    EventQueue.invokeAndWait(new Runnable() {
        ButtonTrue();
    });
}


来源:https://stackoverflow.com/questions/10534844/swing-enabling-buttons-with-delay

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