gpt4 book ai didi

java - 如何制作其 setVisible block 的非模态对话框?

转载 作者:行者123 更新时间:2023-11-30 06:34:29 25 4
gpt4 key购买 nike

在 Swing (J)Dialog 中,setModal设置模态——即对话框是否应该阻止对其他窗口的输入。然后,setVisible文档说模式对话框:

If the dialog is not already visible, this call will not return until the dialog is hidden by calling setVisible(false) or dispose.

确实,如果对话框不是模态的,setVisible立即返回。示例代码:

JDialog jd = new JDialog();
jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

/**
* If set to false, setVisible returns right away.
* If set to true, setVisible blocks until dialog is disposed.
*/
jd.setModal(false);

System.out.println("setting visible");
jd.setVisible(true);
System.out.println("set visible returned");

我想制作一个对话框,不会阻止对其他窗口的输入,但仍然阻止调用者。既然 setVisible 在对话框不是模态时不会阻塞,那么执行此操作的好方法是什么?

为什么 setVisible 的行为取决于模态是否有一些基本原理?

最佳答案

I need to make a dialog that doesn't block input to other windows, but does block the caller so that I know when the dialog has been closed.

我通常不是通过阻止调用者来解决这个问题,而是通过使用某种回调——对话框在完成时调用的一个简单接口(interface)。假设您的对话框有一个“确定”和一个“取消”按钮,您需要区分按下的是哪一个。然后你可以这样做:

public interface DialogCallback {
void ok();
void cancel();
}

public class MyModelessDialog extends JDialog {
private final DialogCallback cbk;
private JButton okButton, cancelButton;

public MyModelessDialog(DialogCallback callback) {
cbk = callback;
setModalityType(ModalityType.MODELESS);

okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
};

cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
};

// Treat closing the dialog the same as pressing "Cancel":
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
};
}

private void onOK() {
cbk.ok();
}

private void onCancel() {
cbk.cancel();
}
}

然后您只需将 DialogCallback 的实例传递给构造函数:

MyModelessDialog dlg = new MyModelessDialog(new DialogCallback() {
public void onOK() {
// react to OK
}
public void onCancel() {
// react to Cancel
}
});

编辑

Is there some rationale why setVisible's behavior depends on the modality?

好吧,这就是模态窗口应该如何工作的,不是吗?模态窗口应该在显示时阻塞当前工作流,而非模态/无模态窗口不应该。参见例如modal windows 上的维基百科页面或 dialog boxes .

关于java - 如何制作其 setVisible block 的非模态对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6895265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com