Search code examples
javaswingappletjdialoginvokelater

making pop up window by using SwingUtilities.invokeLater


I am writing a turn-based game on the internet. I try to pop up a window that should be in front until the input stream is ready. I created smth like this, but it seems that it does not work.

class CustomBlockerDialog extends JDialog {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public CustomBlockerDialog(Frame owner, String text) {
    super(owner, true);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    setSize(300, 100); // Adjust if needed
    setTitle("");
    add(new JLabel(text, SwingConstants.CENTER));
} 
}




final CustomBlockerDialog block = new CustomBlockerDialog(null, "Not your turn");

SwingUtilities.invokeLater(new Runnable() {//A

    @Override
    public void run() {
        System.out.println("show");
        block.setVisible(true);
    }
});


boolean one_write_only = true;
while(in.ready()){ /* C*/ 
    if(one_write_only){
        System.out.println("waiting server");
        one_write_only = false;
    }
};

System.out.println("suppose to hide");

SwingUtilities.invokeLater(new Runnable() {//B

    @Override
    public void run() {
    System.out.println("hide");
    block.setVisible(false);
    }
});

It looks like "A" and "B" are executed after "C" and I have no idea why.


Solution

  • Thanks to Hovercraft Full Of Eels, I created a little different solution which works in my case:

    final SwingWorker<Object,Object> worker2 = new SwingWorker<Object, Object>() {
            public Object doInBackground() throws Exception {
              boolean one_write_only = true;
                while(!in.ready()){ /* C*/ 
                  if(one_write_only){
                    System.out.println("waiting server");
                    one_write_only = false;
                  }
                }
                return one_write_only;
            }
    
            protected void done() {
                try {
                    block.setVisible(false);
                } catch (Exception ignore) {}
            }
    
    };
    worker2.execute();
    block.setVisible(true);