Skip to content

Instantly share code, notes, and snippets.

@kaedroho
Last active October 12, 2015 06:08
Show Gist options
  • Save kaedroho/3982915 to your computer and use it in GitHub Desktop.
Save kaedroho/3982915 to your computer and use it in GitHub Desktop.
Java Dialogs
/**
* Dialogs
* Some handy functions to get various types of data from a user using JoptionPane
* @author Karl Hobley
* @version r23
*/
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.File;
public class Dialogs {
/**
* Displays an input dialog to the user
* @param message Message to be displayed to the user
* @param defaultValue Value to initialise the input box to
* @return String that the user typed in. Null if they cancelled
*/
public static String input(final String message, final Object defaultValue) {
// Display the input dialog
return JOptionPane.showInputDialog(null, message, defaultValue);
}
/**
* Displays an information message to the user
* @param message Message to be displayed to the user
*/
public static void info(final String message) {
// Display the info message
JOptionPane.showMessageDialog(null, message, "Information", JOptionPane.INFORMATION_MESSAGE);
}
/**
* Displays an error message to the user
* @param message Message to be displayed to the user
*/
public static void error(final String message) {
// Display the error message
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Displays a yes/no dialog to the user
* @param message Message for input prompt
* @param cancelOption Set to true to put a cancel option on the box
* @return True if yes pressed, False if no pressed, null if cancel pressed
*/
public static Boolean yesNo(final String message, final boolean cancelOption) {
// Find options
final int options = cancelOption ? JOptionPane.YES_NO_CANCEL_OPTION : JOptionPane.YES_NO_OPTION;
// Show user the dialog
final int answer = JOptionPane.showConfirmDialog(null, message, "Input", options);
// Check answer
switch (answer) {
case JOptionPane.YES_OPTION:
return true;
case JOptionPane.NO_OPTION:
return false;
case JOptionPane.CANCEL_OPTION:
return null;
}
// This will never execute
// It is just to make the compiler happy :)
return null;
}
/**
* Displays a file open/save dialog to the user
* Only allows one type of extension
* @param extensionDescription Description of the extension thats being looked for
* @param extesions List of extensions to look for
* @param openFile Set to true to open file set to false to save file
* @return Filename of the selected file
*/
public static String fileDialog(final String extensionDescription, final String extension, final boolean openFile) {
// Create JFileChooser
final JFileChooser chooser = new JFileChooser();
// Add filename extensions
final FileNameExtensionFilter filter = new FileNameExtensionFilter(extensionDescription + " (*." + extension + ")", extension);
chooser.setFileFilter(filter);
// Loop forever
String fileName = null;
for (;;) {
// Show dialog
final int result = openFile ? chooser.showOpenDialog(null) : chooser.showSaveDialog(null);
// Check result
if (result != JFileChooser.APPROVE_OPTION) {
return null;
}
// Get filename
fileName = chooser.getSelectedFile().getAbsolutePath();
// Check if the file exists
final File f = new File(fileName);
if (f.exists()) {
// Check if the user is trying to save a file
if (!openFile) {
// User attempting to save to a file that exists
final String shortFileName = chooser.getSelectedFile().getName();
final Boolean replaceFile = getBoolean(shortFileName + " already exists. Would you like to replace it?", false);
// Check if the user wants to replace the file
if (replaceFile) {
break;
}
} else {
break;
}
} else {
// Check if the user is trying to open a file
if (openFile) {
// User trying to open a file that doesnt exist
error("File doesn't exist. Please try again.");
} else {
break;
}
}
}
// Return
return fileName;
}
/**
* Displays a list of options to the user and returns the one the user chooses
* @param message Message to be displayed to the user
* @param options The list of options
* @param defaultValue Value that is already set
*/
public static String getOption(final String message, final String[] options, final String defaultValue) {
return (String) JOptionPane.showInputDialog(null, message, "Choose one", JOptionPane.QUESTION_MESSAGE, null, options, defaultValue);
}
/**
* Gets an integer from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @return Integer inputted by user
*/
public static Integer getInteger(final String message, final Integer defaultValue) {
// Call main getInteger function with min and max nulled out
return getInteger(message, defaultValue, null, null);
}
/**
* Gets an integer from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @param minVal Minimum value allowed to input
* @param maxVal Maximum value allowed to input
* @return Integer inputted by user
*/
public static Integer getInteger(final String message, final Integer defaultValue, final Integer min, final Integer max) {
// Loop until return
for (;;) {
// Get input string
final String textInput = input(message, defaultValue);
// Check if the user pressed cancel
if (textInput == null) {
return null;
}
// Attempt to convert to Integer
Integer input;
try {
input = Integer.parseInt(textInput);
} catch (NumberFormatException ex) {
// Display error
if (textInput.equals("")) {
error("Please type a whole number in the box.");
} else {
error("Couldn't recognise \"" + textInput + "\". Make sure that you typed a whole number.");
}
// Run loop again
continue;
}
// Check min
if (min != null && input < min) {
// Display error
error("Number to low! The number must be at least " + min + ".");
// Run loop again
continue;
}
// Check max
if (max != null && input > max) {
// Display error
error("Number to high! The number must not be higher than " + max + ".");
// Run loop again
continue;
}
// Found integer. Return it
return input;
}
}
/**
* Gets a float from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @return Float inputted by user
*/
public static Float getFloat(final String message, final Float defaultValue) {
// Call main getFloat function with min and max nulled out
return getFloat(message, defaultValue, null, null);
}
/**
* Gets a float from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @param minVal Minimum value allowed to input
* @param maxVal Maximum value allowed to input
* @return Float inputted by user
*/
public static Float getFloat(final String message, final Float defaultValue, final Float min, final Float max) {
// Loop until return
for (;;) {
// Get input string
final String textInput = input(message, defaultValue);
// Check if the user pressed cancel
if (textInput == null) {
return null;
}
// Attempt to convert to Float
Float input;
try {
input = Float.parseFloat(textInput);
} catch (NumberFormatException ex) {
// Display error
if (textInput.equals("")) {
error("Please type a number in the box.");
} else {
error("Couldn't recognise \"" + textInput + "\". Make sure that you typed a number.");
}
// Run loop again
continue;
}
// Check min
if (min != null && input < min) {
// Display error
error("Number to low! The number must be at least " + min + ".");
// Run loop again
continue;
}
// Check max
if (max != null && input > max) {
// Display error
error("Number to high! The number must not be higher than " + max + ".");
// Run loop again
continue;
}
// Found float. Return it
return input;
}
}
/**
* Gets a string from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @return String inputted by user
*/
public static String getString(final String message, final String defaultValue) {
// Get string
return getString(message, defaultValue, false);
}
/**
* Gets a string from the user
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @param required Set to true if the string is requried
* @return String inputted by user
*/
public static String getString(final String message, final String defaultValue, final boolean required) {
// Loop until return
for (;;) {
// Get input string
final String textInput = input(message, defaultValue);
// Check if the user pressed cancel
if (textInput == null) {
return null;
}
// If an input is required, make sure the user entered something
if (required && textInput.equals("")) {
// Display error
error("Please type something in the box.");
// Run loop again
continue;
}
// Return the string
return textInput;
}
}
/**
* Gets a boolean from the user
* @param message Message for input prompt
* @return Boolean inputted by user
*/
public static Boolean getBoolean(final String message) {
// Get boolean
return getBoolean(message, true);
}
/**
* Gets a boolean from the user
* @param message Message for input prompt
* @param cancelOption Set to true to put a cancel option on the box
* @return Boolean inputted by user
*/
public static Boolean getBoolean(final String message, final boolean cancelOption) {
// This is equivilant to the yes/no dialog
return yesNo(message, cancelOption);
}
/**
* Checks if an email address is valid
* @param email The email address to check
* @return True if valid, false if not
*/
public static boolean isValidEmailAddress(final String email) {
/*
* I used this as a reference for finding what exactly a valid email address is:
* https://en.wikipedia.org/wiki/Email_mailbox
*/
// Split into 2 tokens (mailbox and domain)
final String[] tokens = email.split("@");
if (tokens.length != 2) {
return false;
}
// Perform checks on both tokens
for (final int token = 0; token < 2; token++) {
// Get token length (needed in both checks, so its more efficient to calculate it only once)
final int tokenLength = tokens[token].length();
// Make sure beginning and last characters are not dots (these are valid in the middle though)
if (tokens[token].charAt(0) == '.' || tokens[token].charAt(tokenLength - 1) == '.') {
return false;
}
// Load valid characters
final String validCharacters = (token == 0)
// Load mailbox valid characters
? "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-/=?^_`{|}~."
// Load domain valid characters
: "abcdefghijklmnopqrstuvwxyz0123456789-.";
// Check that all characters are valid
tokens[token].toLowerCase();
for (final int charNum = 0; charNum < tokenLength; charNum++) {
// Check that this character is in valid characters
if (validCharacters.indexOf(tokens[token].charAt(charNum)) == -1) {
return false; // Character is not in valid characters
}
}
}
// Passed all tests
return true;
}
/**
* Gets a string from the user and checks if it is a valid email address
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @return Email address inputted by user
*/
public static String getEmailAddress(final String message, final String defaultValue) {
// Get email address
return getEmailAddress(message, defaultValue, false);
}
/**
* Gets a string from the user and checks if it is a valid email address
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @param required Set to true if the string is required
* @return Email address inputted by user
*/
public static String getEmailAddress(final String message, final String defaultValue, final boolean required) {
// Loop until return
for (;;) {
// Get input string
final String textInput = getString(message, defaultValue, required);
// Check if the user pressed cancel
if (textInput == null) {
return null;
}
// Bypass validation if blank was inputted but email not required
if (textInput.equals("") && !required) {
return "";
}
// Check that this string is a valid email address
if (!isValidEmailAddress(textInput)) {
// Display error
error("Please enter a valid email address.");
// Run loop again
continue;
}
// Return the string
return textInput;
}
}
/**
* Checks if a telephone number is valid
* @param telephoneNumber The telephone number to check
* @return True if valid, false if not
*/
public static boolean isValidTelephoneNumber(final String telephoneNumber) {
/*
* This checks that the string contains only numbers and spaces
*/
// Check characters
final int stringLength = telephoneNumber.length();
for (int charNum = 0; charNum < stringLength; charNum++) {
// Check if the character is a digit or a space
final char character = telephoneNumber.charAt(charNum);
if (Character.isDigit(character)) {
continue;
} else if (character == ' ') {
continue;
}
// Didn't match any of above, must be an invalid character
return false;
}
// Passed all tests
return true;
}
/**
* Gets a string from the user and checks if it is a valid telephone number
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @return Telephone number inputted by user
*/
public static String getTelephoneNumber(final String message, final String defaultValue) {
// Get telephone number
return getTelephoneNumber(message, defaultValue, false);
}
/**
* Gets a string from the user and checks if it is a valid telephone number
* @param message Message for input prompt
* @param defaultValue Value to initialise the input box to
* @param required Set to true if the string is required
* @return Telephone number inputted by user
*/
public static String getTelephoneNumber(final String message, final String defaultValue, final boolean required) {
// Loop until return
for (;;) {
// Get input string
final String textInput = getString(message, defaultValue, required);
// Check if the user pressed cancel
if (textInput == null) {
return null;
}
// Bypass validation if blank was inputted but telephone number not required
if (textInput.equals("") && !required) {
return "";
}
// Check that this string is a valid telephone number
if (!isValidTelephoneNumber(textInput)) {
// Display error
error("Please enter a valid telephone number.");
// Run loop again
continue;
}
// Return the string
return textInput;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment