2014-07-23 73 views
-1

我正在写一个基于回合的互联网游戏。我尝试弹出一个应该在前面的窗口,直到输入流准备就绪。我创造了这样的行为,但它似乎不起作用。使用SwingUtilities.invokeLater弹出窗口

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); 
    } 
}); 

看起来“A”和“B”在“C”之后执行,我不知道为什么。

+0

............你好??? –

+0

对不起,很久没有发帖了。我记得它,但我有很多工作。 – slawic

回答

0

由于气垫船全鳗鱼,我创建了一个有点不同的解决方案,它在我的情况下工作:

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); 
2

您的问题必须是由于“C”在Swing事件线程上调用,而不是在后台线程中,因为它听起来像“C”阻塞事件线程运行“A”。解决方案:确保“C”不在Swing事件线程上调用。如果是这种情况,并且可以通过运行SwingUtilities.isEventDispatchThread()方法来测试,则不需要所有其他可运行的程序。

// note that this all must be called on the Swing event thread: 
final CustomBlockerDialog block = new CustomBlockerDialog(null, "Not your turn"); 

System.out.println("show"); 
// block.setVisible(true); // !! no this will freeze! 

final SwingWorker<Void, Void> worker = new SwingWorker<>() { 
    public void 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; 
     } 
     } 
    } 
} 

worker.addPropertyChangeListener(new PropertyChangeListener() { 
    public void propertyChanged(PropertyChangeEvent pcEvt) { 
     if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) { 
     System.out.println("hide"); 
     block.setVisible(false); 

     // call worker's get() method here and catch exceptions 
     } 
    } 
}); 

worker.execute(); 

// moved to down here since the dialog is modal!!! 
block.setVisible(true); 

警告:代码没有编译或测试。从袖口输入时可能存在错误。

+0

真的很感谢:) – slawic