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

dispose问题和Container如何释放资源
问1:
		JWindow w=new JWindow();
w.setBounds(200, 500, 200, 200);
w.setVisible(true);
w.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
System.out.println("close");
}
});
w.dispose();


结果:
close
close

输出了2次为什么?

问2:java.awt.Container如何释放资源
Container 没有dispose 方法,setEnabled(false)也是没用的,setVisible(false)只是隐藏罢了


------解决方案--------------------
w.dispose();//这其实是隐藏,并不是关闭,这个jwindow本身没有dispose方法,也没有关闭按钮。隐藏后相当于触发了WindowAdapter,所有会有两次输出。
------解决方案--------------------
setVisible和dispose的区别参考一下API,释放资源可以讲组建设置为空即可,入股已经添加到某个容器中,可以通过他的父对象将其从容器中移除。
------解决方案--------------------
引用:
w.dispose();//这其实是隐藏,并不是关闭,这个jwindow本身没有dispose方法,也没有关闭按钮。隐藏后相当于触发了WindowAdapter,所有会有两次输出。


dispose是释放占用的资源。
------解决方案--------------------
这个看javadoc最清楚了

public void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. 
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions). 

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. 

释放的是native screen resources,但事后可重建,可能还是维护了一些状态信息的,但是dispose之后对window的修改不计在内(dispose之后还能修改啊)