简体   繁体   中英

Using JOptionPane.YES_NO_OPTIONS

Here's my problem, I'm trying to get this bit of code to work so that in my GUI, when I click on yes, the product is added (that bit of code is still to be developed) and the addproductwindow closes, but when no is clicked the JOptionPane closes, but the add product window remains open. (the System.out.print(" no "); ) was me just testing what came out from the inputs.

@Override
public void actionPerformed(ActionEvent e) {
    int dialogButton = JOptionPane.YES_NO_OPTION;

    JOptionPane.showConfirmDialog (null, "Do you want to add Product: ","Confirmation",dialogButton);

   if (dialogButton == 1){
       System.out.println(" no ");

    } else { 
      addProductWindow.dispose();
    }
}   

When using JOptionPane.showConfirmDialog (...) you need to check which button was clicked by the user.

The basic code is:

int result = JOptionPane.showConfirmDialog (...);

if (result == JOptionPane.YES_OPTION)
    //  do something

Read the section from the Swing tutorial on How to Use Dialogs for more information and working examples.

if (dialogButton == 1)

Don't use "magic numbers". Nobody knows what "1" means. The API will have variable for you do use that are more descriptive.

For addProductWindow to close, you have to call addProductWindow.dispose() method in the if block too.

@Override
public void actionPerformed(ActionEvent e) {
    int dialogButton = JOptionPane.YES_NO_OPTION;

    JOptionPane.showConfirmDialog(null, "Do you want to add Product: ", "Confirmation", dialogButton);

    if (dialogButton == JOptionPane.YES_OPTION) {

        addProductWindow.dispose();       // you forgot this
    } else {
        System.out.println(" no ");
        addProductWindow.dispose();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM