从JDialog返回值; dispose(),setVisible(false)-示例 [英] Returning value from JDialog; dispose(), setVisible(false) - example

查看:233
本文介绍了从JDialog返回值; dispose(),setVisible(false)-示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,这个问题在此处
,但我想举一些非常具体的示例...我只是不确定我是否做对了。

I know, that this question appears quite frequently in SO like here: but I would like to present some very specific example... I'm simply not sure if I make things right.

我有一个JDialog,可以在其中键入一些值,选择一些复选框...等等...
我也有一些在MyDialog中创建的Response对象

I've got a JDialog in which I can type some values, select some checkboxes... whatever... I've got also some Response object created in MyDialog which represents the MyDialog's "answer".

在调用/创建JDialog的JFrame中:

In JFrame which calls/creates JDialog:

MyDialog d = new MyDialog(this, ...);
d.showDialog();
// After MyDialog is closed (it's modal):
MyDialog.Response dialogResponse = d.getDialogResponse();
// Do something with response...

在对话框中(对话框可以通过关闭点击保存按钮):

In Dialog (dialog can be closed by clicking "Save" button):

btnSave.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        dialogResponse = prepareResponse(); // prepares response on the basis of some data introduced by a user; dialogResponse is called from JFrame after Dialog is closed
        setVisible(false);
        dispose();  // <-- Important
    }
});

我的问题是:
此解决方案有效,我的意思是, MyDialog.Response dialogResponse = d.getDialogResponse(); 返回正确的值,但是...
如果我使用dispose()关闭对话框,则所有对话框的资源都可以被垃圾回收(不必...很难预测,对吗?)。因此,以这种方式检索对话框的响应是否正确...也许在这种情况下,我应该只写 setVisible(false); 而没有 dispose( )

My question is: This solution works, I mean, the line MyDialog.Response dialogResponse = d.getDialogResponse(); returns proper values, but... if I close the dialog using dispose(), all dialog's resources can be garbage collected (don't have to... hard to predict, am I right?). So is it correct to retrieve my dialog's response it that way... Maybe in this case I should write only setVisible(false); without dispose().

推荐答案

引自 Javadocs


通过重建本机资源并随后调用pack或show,可以再次显示Window及其子组件。 重新创建的Window及其子组件的状态将与放置Window时这些对象的状态相同(不考虑这些动作之间的其他修改)。

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).

因此,您的回复将被保留。 dispose()所做的所有操作都是在释放本机屏幕资源,其他成员未标记为垃圾回收。

So, your Response will be kept. All dispose() does is releasing the native screen resources, other members aren't marked for garbage collection.

另外,如果您想更加确定,则可以在检索到响应对象之后立即调用 dispose()

Also, if you want to be extra sure, you could just call dispose() right after you retrieved your response object.

这篇关于从JDialog返回值; dispose(),setVisible(false)-示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆