java中的dispose()方法
(2009-01-22 21:58:36)
标签:
javait |
分类: IT技术 |
先来看看 JAVA 1.5 的帮助文档的原文 - dispose - public void dispose()
注:当 Java 虚拟机 (VM) 中最后的可显示窗口被移除后,虚拟机可能会终止。
呵呵~顺便写个程序,简单验证一下:
By Noel @ 程序员之家 // 验证dispose()方法,窗体是否能被正确还原
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/////////////////////////// MyFrame 主窗体 /////////////////////////////////
class MyFrame extends JFrame implements ActionListener {
JButton btnEvt=new JButton("生成窗体");
JButton btnEvt1=new JButton("恢复子窗体");
JTextArea txtArea =new JTextArea(5,15);
static int flag=0;
//标记子窗体是否被生成
subFrame subfrm;
public MyFrame() {
super("主窗体");
this.setBounds(20,20,300,200);
Container cPane=getContentPane();
cPane.setLayout(new FlowLayout());
//在按钮上添加监听器
cPane.add(btnEvt);
btnEvt.addActionListener(this);
cPane.add(btnEvt1);
btnEvt1.addActionListener(this);
this.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent e) { System.exit(0); } }
);
this.setVisible(true);
}
//实现按钮中方法
public void actionPerformed(ActionEvent ae) {
if( flag==0 && (ae.getSource()).equals(btnEvt)) {
flag=1;
btnEvt.setEnabled(false);
subfrm=new subFrame(); //生成子窗体 }
}
else
{
subfrm.setVisible(true); //恢复子窗体 }
}
}
//测试用主函数
public static void main(String str[]) { MyFrame frm=new MyFrame();
} }
///////////////////////// 子窗体 //////////////////////////////
class subFrame extends JFrame {
JLabel lblsub=new JLabel("点击右上角关闭按钮关闭。");
//设置JRadioButton目的为了标记窗体状态 //检查是否能被正确还原
JRadioButton rbtn1=new JRadioButton("1");
JRadioButton rbtn2=new JRadioButton("2");
JRadioButton rbtn3=new JRadioButton("3");
public subFrame() {
super("子窗体");
this.setBounds(30,40,200,300);
Container cPane=getContentPane();
cPane.setLayout(new FlowLayout());
ButtonGroup bg =new ButtonGroup();
bg.add(rbtn1);
bg.add(rbtn2);
bg.add(rbtn3);
cPane.add(rbtn1);
cPane.add(rbtn2);
cPane.add(rbtn3);
cPane.add(lblsub);
this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) {
//可切换两种不同的方法,不过表象上两种方法运行时没有区别
subFrame.this.dispose();
//subFrame.this.setVisible(false);
} } );
//this.setVisible(true);
}
}
======================================================================================
我的理解是dispose是 java.awt.Windows类的方法,它的作用是销毁程序中指定的图形界面资源,对数据资源不产生影响,所以当我们在SWing或是AWT中的图形界面组件时如果调用它,组建内的数据对象不会消失,只有在这些数据资源其他地方没有再使用后才会由垃圾回收机制处理掉。

加载中…