GUI threading in java

后端 未结 3 1387
天命终不由人
天命终不由人 2020-12-22 08:34

I\'m trying to code a simple game in Java. The basic structure is a single JFrame with different JPanels that I add/remove at different times. At s

相关标签:
3条回答
  • 2020-12-22 09:02

    never really never use Thread.sleep(1000); during EDT, this code caused freeze on GUI is un_resposible, untill a new event invoke EDT or mouse hover over can alive this container too

    1) there are two ways how to dealy any event(s) in the Swing GUI, by implements

    • Swing Timer

    • delaying by using Thread.sleep(1000); in the SwingWorker

    0 讨论(0)
  • 2020-12-22 09:17

    You can start some code with a time delay using TimerTask:

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            invokeLater(); // This starts after [delay] ms 
            // and - if given - will run every [period] ms.
        }
    }, delay, period);
    

    You could solve your problem with this, though it won't be a pretty solution.

    // edit: (see comments) you should synchronize accesses to the gui properly, else it will give you errors.

    0 讨论(0)
  • 2020-12-22 09:23

    The layout and painting must be done in EDT. Use SwingUtilities.invokeAndWait to call the validate() and repaint()

    0 讨论(0)
提交回复
热议问题