JOptionPane Passing Custom Buttons

In the example I linked to you previous question, the buttons use the JOptionPane#setValue method to set the return value. This allows you to continue using the API as normal, while providing you with the customisation your after.

            final JButton okay = new JButton("Ok");
            okay.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane pane = getOptionPane((JComponent)e.getSource());
                    // set the value of the option pane
                    pane.setValue(JOptionPane.OK_OPTION);
                }
            });

Take a closer look at Disable ok button on JOptionPane.dialog until user gives an input

Updated

I’ve gone back through the code and correct the actionPerformed methods to enable it to return a valid value…

final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane pane = getOptionPane((JComponent)e.getSource());
        pane.setValue(okay);
    }
});
okay.setEnabled(false);
final JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane pane = getOptionPane((JComponent)e.getSource());
        pane.setValue(cancel);
    }
});

The value returned by the index of the value in the options array (last parameter)

So, for example…

int value = JOptionPane.showOptionDialog(
     null, 
     field, 
     "Get", 
     JOptionPane.YES_NO_OPTION, 
     JOptionPane.QUESTION_MESSAGE, 
     null, 
     new Object[]{okay, cancel}, 
     okay);

If the user clicks the okay button, the return value will be 0, or if they select the cancel button, it will be 1

Leave a Comment