javaswingthread-safetyevent-dispatch-threadsetbounds

Is setBounds() called in the EDT?


Is the setBounds() method of a Component like JPanel called on the Event Dispatch Thread? I am asking this because I am writing a program that draws platforms and uses a Swing Timer to move them up. I override the setBounds() method so that every time the JPanel is resized, the platforms will resize too. I just want to make sure that setBounds() doesn't resize the platforms while the Timer is moving them. Also, would it be better to use a WindowListener to check if the JPanel was resized?


Solution

  • setBounds() will be called on the EDT by Swing code, but you have to ensure your code's own invocations of setBounds() also only calls it on the EDT. If you can ensure all calls of setBounds() occur on the EDT, then you shouldn't have to worry about setBounds() being executed while your SwingTimer is being executed because SwingTimers also execute on the EDT by default (so they won't execute at the same time).

    Also I never seen someone override setBounds() so I do wonder if there's not an alternative solution such as just querying the bounds every time your SwingTimer executes. Using a listener listening for window resizes like you say does sound much better.