日期:2014-05-20  浏览次数:20620 次

关于模态对话框和非模态对话框的问题
关于模态对话框和非模态对话框的问题:
请高手看一下这个代码,非模态对话框没有问题,模态对话框有问题。改变setVisible(true)是位置就好了。莫非   模态对话框中setVisible(true)必须放在事件处理的后面,没道理啊!高手帮忙解决一下啊,想了一上午了!

import   java.awt.*;
import   java.awt.event.*;

public   class   TestDialog   extends   Frame  
{
public   TestDialog()
{
Frame   f   =   new   Frame( "TestDialog ");
f.setSize(300,300);
Button   b1   =   new   Button( "打开模态对话框 ");
Button   b2   =   new   Button( "打开非模态对话框 ");
f.add(b1, "Center ");
f.add(b2, "East ");
f.setVisible(true);
b1.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)
{
new   MyDialog0(TestDialog.this, "model ",true);
}
});
b2.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)
{
new   MyDialog0(TestDialog.this, "modalless   dialog ",false);
}
});
f.addWindowListener(new   WindowAdapter()
{
      public     void   windowClosing(WindowEvent   e)  
      {
      e.getWindow().setVisible(false);
      e.getWindow().dispose();
      System.exit(0);
      }
});
}
public   static   void   main(String[]args)
{
new   TestDialog();
}
}
class   MyDialog0   extends   Dialog
{
public   MyDialog0(TestDialog   owner,String   title,boolean   modal)
{
super(owner,title,modal);
this.setBounds(0,0,200,200);

Button   t1   =   new   Button( "应用 ");
Button   t2   =   new   Button( "确定 ");
this.add(t1, "Center ");
this.add(t2, "East ");
setVisible(true);//注意:如果这一句放在事件处理的后面就不会有问题。

t1.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)  
{
System.out.println(e.getActionCommand());
}
});
t2.addActionListener(new   ActionListener()
{
public   void   actionPerformed(ActionEvent   e)  
{
System.out.println(e.getActionCommand());
MyDialog0.this.dispose();
}
});
//setVisible(true);     放在这里就不会有问题。
}
}



------解决方案--------------------
加在后面好用就在后面加好了嘛。

这里是模态对话框的特点决定的。

模态对话框显示之后会接收所有消息,在他关闭之前无法对其他的窗口事件进行相应。

说简单一点,就是你模态对话框setVisible(true)之后,在他被关掉之前任何处理都不会被执行。你在setVisible后面加一句System.out.println看看有没有被执行到就知道了