Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOptionPane handling ok, cancel and x button

There is one problem I am facing with my JOptionPane if I don't key in anything,no matter what I press(the ok,cancel or the x button(the top right button in the JOptionPane)), it will prompt me until the I key in a positive value. but I only want the prompt to happen when i pressed ok.

If I click on cancel or the x button(the top right button in the JOptionPane), it will close the JOptionPane

How can I do this?

import javax.swing.JOptionPane;

public class OptionPane {
    public static void main(final String[] args) {
        int value = 0;
        boolean isPositive = false , isNumeric = true;
        do {
            try {
                value = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter value?", null));
            } catch (NumberFormatException e) {
                System.out.println("*** Please enter an integer ***");
                isNumeric = false;
            }

             if(isNumeric) {
                if(value <= 0) {
                    System.out.println("value cannot be 0 or negative");
                }

                else {
                    System.out.println("value is positive");
                    isPositive = true;
                }
            }
        }while(!isPositive);
    }
}
like image 716
user3879568 Avatar asked Sep 01 '25 17:09

user3879568


2 Answers

The basic approach for this can look like I've showed below:

Updated after @MadProgrammer comment.

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DemoJOption {
    public static void main(String args[]) {
        int n = JOptionPane.showOptionDialog(new JFrame(), "Message", 
        "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, 
        null, new Object[] {"Yes", "No"}, JOptionPane.YES_OPTION);

        if (n == JOptionPane.YES_OPTION) {
            System.out.println("Yes");
        } else if (n == JOptionPane.NO_OPTION) {
            System.out.println("No");
        } else if (n == JOptionPane.CLOSED_OPTION) {
            System.out.println("Closed by hitting the cross");
        }
    }
}
like image 115
bluevoxel Avatar answered Sep 04 '25 07:09

bluevoxel


JoptionPane#showInputDialog returns user's input, or null meaning the user canceled the input.

So instead of directly parsing the return value. First check if it is null (User Cancelled) then do nothing if not null then parse for the integer value

like image 28
Sanjeev Avatar answered Sep 04 '25 07:09

Sanjeev