先看程序,比较简单的。
package com.jtest;import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
class MyDialog extends JDialog
{
private JLabel label=new JLabel("请输入姓名:");
private TextField tf=new TextField(10);
private JButton button=new JButton("ok");
public MyDialog(JFrame parent)
{
super(parent,"提示",true);
Container c=getContentPane();

button.addActionListener(new ActionListener()
{ @Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dispose();

}

});
c.setLayout(new FlowLayout());
c.add(label);
c.add(tf);
c.add(button);
pack();

}
public String getText()
{
return tf.getText();
}

}public class DialogDemo extends JFrame
{
private JButton button=new JButton("提交");
private TextField tf=new TextField(10);
private MyDialog dialog=new MyDialog(this);

public DialogDemo(String title)
{
super(title);
Container c=this.getContentPane();

tf.setEditable(false);
button.addActionListener(new ActionListener()
{ @Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
dialog.setVisible(true);
tf.setText(dialog.getText());
System.out.println("模态测试:  "+dialog.getText());



}

});
c.setLayout(new FlowLayout());
c.add(button);
c.add(tf);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
public static void main(String[] args)
{
new DialogDemo("标题");
}
}
问题:如红色地方显示, swing组件里面的模态对话框JDialog调用dispose()方法,释放了对话框资源,为什么还能调用dialog.getText()方法得到文本框的值呢,不是释放了对话框的资源吗??

解决方案 »

  1.   

    在JDK API文档中对于dispose方法有说明:
      释放由此 Window、其子组件及其拥有的所有子组件所使用的所有本机屏幕资源。即这些 Component 的资源将被破坏,它们使用的所有内存都将返回到操作系统,并将它们标记为不可显示。 通过随后对 pack 或 show(1.6后为setVisible()) 的调用重新构造本机资源,可以再次显示 Window 及其子组件。重新创建的 Window 及其子组件的状态在移除 Window 的点上与这些对象的状态将是一样的(不考虑这些操作之间的其他更改)。
    注:当 Java 虚拟机 (VM) 中最后的可显示窗口被移除后,虚拟机可能会终止。
        实际上就是说明了两层意思: 1.使用dispose()方法关闭窗体会释放该窗体的占用的部分资源,不过呢不是全部的,如上面说的,只是屏幕资源。2.使用dispose()方法关闭的窗体可以使用pack 或 show 方法恢复,并且可以恢复到dispose前的状态。楼主你可以重现点击JFrame上的按钮弹出对话框看一下,显示的数据是你前一次填入的。