Over a million developers have joined DZone.

Get Input With JOptionPane

DZone's Guide to

Get Input With JOptionPane

· ·
Free Resource
// 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 =
      public static final Pattern DOUBLE = 

	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)


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}