Search code examples
javaswingjoptionpane

ConfirmDialog not working


I'm trying to create a register window when i click a button from my "main" JFrame window. For some reason showConfirmDialog won't take OK_CANCEL_OPTION as an argument. The RegTemplate is a JPanel with the stuff i want in my register window.

The strange thing is that I watch some example code that im 100% sure works and I have checked mine against this one but I can't find any real difference. The Marathon class is my "main" program window by the way.

Please tell my whats wrong here, I hope this code is enough.

class createListener implements ActionListener{
    public void actionPerformed(ActionEvent ave){
    RegTemplate reg = new RegTemplate();
    int choice = showConfirmDialog(Marathon.this, reg, "New participant", OK_CANCEL_OPTION);
    if (choice != OK_OPTION)
            return;
    DO SOMETHING IF OK IS CLICKED
    }
}

Solution

  • Unless your class extends from JOptionPane then OK_CANCEL_OPTION is an unknown identifier and your code won't compile. It should be JOptionPane.OK_CANCEL_OPTION instead which is a public constant defined in JOptionPane class.

    Try this:

    int choice = showConfirmDialog(Marathon.this, reg, "New participant", JOptionPane.OK_CANCEL_OPTION);
        if (choice != JOptionPane.OK_OPTION){ ... }
    

    Also you should take a look to Understanding Instance and Class Members article.


    Edit

    I bring this up from the comments because it might be useful:

    I added a static import of JOptionPane.*; I made it static since i will reuse it in several different popup windows, from what I understand this might be an ok solution.

    I think it is a unusual but very valid solution indeed, as stated in this article: Static Imports