Search code examples
javaswingjoptionpane

JOptionPane action listener posting on exit


I created a button called addSupplier applied to a frame, then I created an action listener so once the addSupplier button is pressed it would create a JOptionPane which has a panel attached with JTextFields.

        addSupplier.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae) {
            JOptionPane.showMessageDialog(null,addSupplierPanel,"Add new supplier", JOptionPane.PLAIN_MESSAGE);
            suppNameInsert = suppNameIn.getText();
            System.out.println(suppNameInsert);
        }
    });

The purpose of this JOptionPane is to add information to the JTextFields to then be processed and sent into a MySQL database, however, because the JOptionPane is opening in the action listener if I press Okay OR the 'X' out button it will print whatever is in the JTextField.

I only want this to happen when I press 'OKAY' but I assume that I will have to go about generating the JOptionPane in a separate way?


Solution

  • Changing the showXXX(...) changes the input and content of the pane but doesn't stop the exit out button from being seen as a button press?

    You need to check the int parameter that was returned from the showXXX(….) method. This value will tell you which button was clicked.

    Something like:

    int result = JOptionPane.showConfirmDialog(…);
    
    if(result == JOptionPane.YES_OPTION)
    {
        // do your processing here
    }