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);
}
}
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");
}
}
}