DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Get Input With JOptionPane
// Gets user input using JOPtionPanes.
// -Validates as datatyoe
// -Continues to loop for valid input or user quits.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
public static final Pattern CHARACTER = Pattern.compile("\\S.*?");
public static final Pattern UNSIGNED_INT = Pattern.compile("\\d+.*?");
public static final Pattern INT = Pattern.compile("[+-]?\\d+.*?");
public static final Pattern UNSIGNED_DOUBLE =
Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");
public static final Pattern DOUBLE =
Pattern.compile("[+-]?((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?");
public static double getIntInput (String promptMsg)
{
boolean validInput = false;
double returnVal;
String inString = "";
while (!validInput)
{
inString = JOptionPane.showInputDialog(null, promptMsg);
Matcher m = INT.matcher(inString);
validInput = m.find(); // RETURN FROM VALIDATEDOUBLE METHOD
if (!validInput)
{
showErrorPane("VALIDATION ERROR", "Could not validate input. This is most likely due to either:\n1. Input was not a valid number (contains only #'s and decimal point).\n2. The number was negative (negative #'s not valid).");
}
}
returnVal = Integer.parseInt(inString);
return returnVal;
}
public static void showErrorPane(String msg, String title) {
int selection = JOptionPane.showOptionDialog(null,
title, msg, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null,
new String[]{"Try Again", "Exit"}, "Try Again");
if (selection == JOptionPane.NO_OPTION)
System.exit(0);
}





