Search code examples
javaswingjframejpaneljoptionpane

how to apply existed buttons to yes/no button(s)?


I have a JFrame have "Add new user" button, a AddUser class which extends JPanel

Inside of AddUser class have name, job,....,Add and "Clear all" buttons

I'm using showOptionDialog to open AddUser

AddUser addPanel = new AddUser();
JButton[] temp = new JButton[1];
temp[0] = AddUser.jButton1;        //this is add button

int option = JOptionPane.showOptionDialog(rootPane, addPanel,"Add new user"
     ,JOptionPane.YES_OPTION, JOptionPane.INFORMATION_MESSAGE, null, temp, null);

the showOptionDialog require Object[] so I created JButton[] then throw add button in

It does open add pane but when I click add button, the pane doesn't turn off


Solution

  • If you provide JButton Components to JOptionDialog as options, you need to set the users selected value manually in the Buttons action listener.
    This is described in (I copied the getOptionPane code from answer 2):

    Here is some example code which uses a custom JButton for a JOptionDialog:

    class OptionPanetest {
        public static void main(String[] args) {
            new OptionPanetest();
        }
    
        protected JOptionPane getOptionPane(JComponent parent) {
            JOptionPane pane = null;
            if (!(parent instanceof JOptionPane)) {
                pane = getOptionPane((JComponent)parent.getParent());
            } else {
                pane = (JOptionPane) parent;
            }
            return pane;    
        }
    
        public OptionPanetest() {
            JFrame testFrame = new JFrame();
            testFrame.setSize(500, 500);
    
            JPanel addPanel = new JPanel();
            addPanel.setLayout(new GridLayout(1,1));
    
            JButton testButton = new JButton("New Button");
            testButton.addActionListener(e -> {
                System.out.println("Test Button Was Pressed");
    
                JButton testButtonInstance = (JButton)e.getSource();
                JOptionPane pane = getOptionPane(testButtonInstance);
                pane.setValue(testButtonInstance);
            });
    
            testFrame.setLocationRelativeTo(null);
            testFrame.setVisible(true);
    
            Object[] options = {testButton};
    
            int option = JOptionPane.showOptionDialog(null, "This is a test", "Add Panel Test", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        }
    }