Search code examples
javaswingconcurrencyfuturecompletion-service

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(...). 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. Instead, I had thought to use somehow a CompletionService, but I'm not able to think how to do it exactly. 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. How to do this?


Solution

  • The simplest option is the embed your panel in a JDialog which is modal setModal(true).

    This way you can have a static method which initialize your panel and whatever, invoke the setVisible(true) (blocking since the dialog is modal). 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();
    }