Question

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!

Was it helpful?

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.
}

OTHER TIPS

You can use 'ItemListener'

which just like 'ActionListener'. if statement should in 'ItemListener'. This will check the items and generate your required pop-up 'JOptionPane' Check this out. And one more thing; your if statement must be like below if you say ' ("go" or "ti").'

if(fn.getText().equals("") || !(go.isSelected()) || !(ti.isSelected())){
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top