简体   繁体   English

Java-在JPanel中获取选择的选项而无需轮询

[英]Java - Get chosen option in JPanel without polling

I've got a JPanel which instances another JPanel in a pretty similar way as JOptionPane.showMessageDialog(...) . 我有一个JPanel,它以与JOptionPane.showMessageDialog(...)类似的方式实例化另一个JPanel。 But I don't use this option because I want to change the size, message, buttons positions, and some more stuff. 但是我不使用此选项,因为我想更改大小,消息,按钮位置以及其他一些内容。 But the final utility must be the same, returning the selected option as soon as it's chosen. 但是最终的实用程序必须相同,选择后立即返回所选的选项。 The thing is that I don't want to have to poll an attribute which may be initialized to null until it's changed from the actionPerformed(...) method. 事实是,我不想轮询可能会被初始化为null的属性,直到从actionPerformed(...)方法更改它为止。 Instead, I had thought to use somehow a CompletionService , but I'm not able to think how to do it exactly. 相反,我曾考虑过以某种方式使用CompletionService ,但我无法考虑如何精确地做到这一点。 How shall I define it? 我该如何定义? Because I guess the Future has to be picked in a getSelectedOption() method, but it has to be generated in the actionPerformed(...) one. 因为我猜想Future必须在getSelectedOption()方法中选择,但必须在actionPerformed(...)生成。 How to do this? 这个怎么做?

The simplest option is the embed your panel in a JDialog which is modal setModal(true) . 最简单的选择是将面板嵌入到模态setModal(true)的JDialog中。

This way you can have a static method which initialize your panel and whatever, invoke the setVisible(true) (blocking since the dialog is modal). 这样,您可以有一个静态方法来初始化面板,然后调用setVisible(true) (由于对话框是模式对话框而被阻塞)。 Then once the user click the Ok button (which close the dialog), you can retrieve the selected option. 然后,一旦用户单击“确定”按钮(将关闭对话框),您就可以检索所选的选项。

public static MyOption showMyDialog() {
    final JDialog myDialog = new JDialog();
    myDialog.add(myPanel);
    myDialog.setModal(true);
    myDialog.setVisible(true); // blocker since the dialog is modal

    return myPanel.getSelectedOption();
}

您可以编写JOptionPane的子类并进行所需的布局,并且仍然使用return方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM