Search code examples
javaswingdialogjoptionpane

JOptionPane, closing and cancel not working while validating JTextField


I have a JOptionPane with a JTextField:

private void imageFilePanel(){
    JRadioButton go = new JRadioButton("Grid Object");
    JRadioButton ti = new JRadioButton("Tile Image");
    JTextField fn = new JTextField(15);
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    panel.add(fn);
    panel.add(go);
    panel.add(ti);
    JOptionPane.showOptionDialog(null, panel, "Name Image", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

    if(fn.getText().equals("") || !(go.isSelected()) && !(ti.isSelected())){
        JOptionPane.showMessageDialog(frame, "Complete required fields.", "Error Message", JOptionPane.ERROR_MESSAGE);
        imageFilePanel();
    }
}

I don't want the user to proceed to the next step unless they fill in the JTextField "fn" and choose one of the JRadioButtons ("go" or "ti").

However, my code right now goes through the if statement when the user clicks the window close or cancel button. This is not the behavior I want; I want the if statement to be evaluated only when the user attempts to press the "OK" button without filling in "fn", without choosing "go" or "ti", or without both.

Any advice is welcome!


Solution

  • Actually if you lock at showOptionDialog you will see that it returns an int holding the button that got pressed in the dialog, so you can use that int variable to determine weather to execute you statement or not.

    For Example:

    int result = JOptionPane.showOptionDialog(null, panel, "Name Image", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
    
    if(result == JOptionPane.YES_OPTION) {
         //your code.
    }