InvokeLater() - will just once be enough?

168 Views Asked by At

I use the recommended code to start my interactive program, which uses Swing. :

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            createAndShowGUI();
          } } ) };

It creates a JFrame, call it "Foo", and ends when the user closes that window (by using the OS' Close- Window X icon or another OS way to close the app)

I want to display another window, "Bar", get user input, close that window with my own Swing calls, and then display the "Foo" window.

I could reuse the same JFrame for Foo and Bar, and just clear it out in-between. But I prefer to make each of them more independent in their design. So, an ActionListener in Foo would need to close Foo's frame, and call the code that displays Bar.

Do I need to use InvokeLater() to call the code that displays Bar? To get more design independence, should my main() be starting and synchronizing two threads?

2

There are 2 best solutions below

0
On

I could reuse the same JFrame for Foo and Bar, and just clear it out in-between. But I prefer to make each of them more independent in their design. So, an ActionListener in Foo would need to close Foo's frame, and call the code that displays Bar.

Do I need to use InvokeLater() to call the code that displays Bar? To get more design independence, I am unclear on the operation of the EDT.

  • you would use pack() and setVisible(true) wrapped into invokeLater in all cases for

    1. for new Top-Level Container - alyways

    2. for container created but never dispayed - always

    3. for container once visible, then hidden and again visible on the screen - always

    4. doesn't matter if is invoked from Swing Listener (by default on EDT) or not

  • to my point 3rd. to avoiding any unwanted Graphics lacks in the case that you reused Top-Level Container (is specifics, very short moment, but could be visible, but not, never annoying)

    • old value is visible, then immediatelly refreshed to current

    • old JComponent is visible, then immediatelly refreshed with current JComponents

    • relayout/ pack() , the same issue as a.m.

  • invokeLater to delay (in most casses with success) this event to the end of EDT

  • see my view translated to the code demonstration about

4
On

User triggered action listener code is executed in the EDT, so you do not need to wrap it again. That said, it may well be that using CardLayout would be more appropriate than multiple frames.