Over a million developers have joined DZone.

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


Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}