Search code examples
javaswingjoptionpane

JOptionPane Grey Out One Button


I need to use a JOptionPane to give the user two options. Depending on previous actions though one of the buttons may need to be disabled.

Is it possible with JOptionPane to have the ability to set either of the buttons to be disabled or enabled?

How can I do this?


Solution

  • It's easy if you use JButtons:

        public class Test
    {
        public static void main(String[] args)
        {
            final JButton option1 = new JButton("option1");
            final JButton option2 = new JButton("option2");
            option1.setEnabled(false);
            // option2.setEnabled(false);
            option1.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent arg0)
                {
                    // code here
                }
            });
            option2.addActionListener(new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    // code here
                }
            });
            JOptionPane.showOptionDialog(null, "hello", "The Title", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, new JButton[]
            { option1, option2 }, option1);
        }
    }