import javax.swing.JOptionPane; // The 'JOptionPane' class contains numerous // static methods that can be called directly; // the dialog boxes produced by these methods // can be extensively customized // For extensive information on the 'JOptionPane' class, see // https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html public class JOptionPaneDemo { public static void main(String[] args) { // ============================================================ // Basic string input String name = JOptionPane.showInputDialog("What is your name?"); if (name != null && !name.trim().equals("")) JOptionPane.showMessageDialog(null, "You gave your name as: " + name); else JOptionPane.showMessageDialog(null, "You did not give your name!"); // ============================================================ // Numerical input with a loop boolean badInput; int age = 0; do { badInput = false; try { age = Integer.parseInt(JOptionPane.showInputDialog("How old are you?")); } catch (Exception error) { JOptionPane.showMessageDialog(null, "You need to enter an integer.\nPlease try again."); badInput = true; } } while (badInput); JOptionPane.showMessageDialog(null, "You are " + age + " years old."); // ============================================================ // A customized Confirmation Dialog Box and Message Dialog Box; note // that the message type for the Message Dialog box determines which // icon is displayed int answer = JOptionPane.showConfirmDialog(null, "Do you like this demo program?", "Question from Dave", JOptionPane.YES_NO_OPTION); if (answer == 0) JOptionPane.showMessageDialog(null, "You answered YES.", "Thanks for the feedback!", JOptionPane.PLAIN_MESSAGE); if (answer == 1) JOptionPane.showMessageDialog(null, "You answered NO.", "Thanks for the feedback!", JOptionPane.PLAIN_MESSAGE); if (answer == 2 || answer == -1) JOptionPane.showMessageDialog(null, "You did not answer the question!", "No Feedback Given", JOptionPane.ERROR_MESSAGE); // ============================================================ // An extremely customized Input Dialog Box String[] colors = new String[] {"red", "green", "blue", "yellow"}; String choice = (String)JOptionPane.showInputDialog(null, "What is your favorite color?", "Color Chooser", JOptionPane.INFORMATION_MESSAGE, null, colors, colors[0]); if (choice != null) JOptionPane.showMessageDialog(null, "I agree that " + choice + " is a very nice color."); else JOptionPane.showMessageDialog(null, "I'm sad that you didn't choose a color."); System.exit(0); } }