Question about JOptionPane.showInputDialog

How do I know when the CANCEL button is pressed in response to JOptionOptionPane.showInputDialog?
Thanks for the help!

Try this
import javax.swing.JOptionPane;
class TestJOptionPane
  public TestJOptionPane()
    String response = JOptionPane.showInputDialog("enter something");
    if(response == null) JOptionPane.showMessageDialog(null,"cancel/escape or 'x' selected");
    else if(response.equals("")) JOptionPane.showMessageDialog(null,"OK button, but nothing entered");
    else JOptionPane.showMessageDialog(null,"OK button, you entered "+response);
    System.exit(0);
  public static void main(String args[]){new TestJOptionPane();}
}

Similar Messages

  • A question about JOptionPane.showOptionDialog()?

    one problem confused me.
    import javax.swing.*;
    class Test
    public Test()
         int n;
         String title;
         Object[] message = new Object[3];
         Object[] obj = new Object[2];
         message[0] = "Name ";
         message[1] = "Age";
         title = "Information";
         obj[0] = "OK";
         obj[1] = "Cancel";
         n = JOptionPane.showOptionDialog(null,
         message,
         title,
    JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.INFORMATION_MESSAGE,
                        null,
                        obj,
                        obj[0]);               
         public static void main(String[] args)
              new Test();
    i run the java compiler in command line.
    c:\proj1>javac Test.java
    c:\proj1>java Test
    Having done the program, i found that command line didnot return to "c:\proj1>"
    only after "Ctrl-c" can that return back to the "c:\proj1". i didnot meet this problem when i run other java projects.
    what's the problem?
    thanks!

    Implement a call to System.exit(0) at the point you want the programm to close.
    (Depending on the return code of your option dialog)

  • QUESTION ABOUT JOPTIONPANES

    Does anybody knows how can I change the font of the String text messagedialog in a JOptionPane, I kNow how to control de icon but not the font of this text, I would apreciate any help , thankyou very much

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class OptionPaneDemo extends JFrame {
         JFrame jf;
         OptionPaneDemo(){
              jf = new JFrame();
              jf.setVisible(true);
              jf.validate();
              jf.setBounds(100,100,200,200);
              //jf.pack();
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container cp = jf.getContentPane();
              JOptionPane jop = new JOptionPane();
              jop.showMessageDialog(jf,"<HTML><FONT SIZE=\"32\">This is Swing</FONT></HTML>");
         public static void main (String args[]){
              OptionPaneDemo opd = new OptionPaneDemo();
    }

  • JOptionPane.showInputDialog

    Hi,
    I have a question about JOptionPane.showInputDialog(...), there is a method that accepts an object array for its parameter, when the array size exceeds a certain bound the final dialog will contains a JList in it. When I click the item of the JList then click cancel the null will be returned, but when double clicking item and then cancel the item will be returned. Partial of my code is:
    String[] available = toSortedStringArray(mapColumn.keys());
    if (available.length == 0)
         return;
    Object selected =
         JOptionPane.showInputDialog(
              FilterControl.this,
              "Select Column",
    JOptionPane.QUESTION_MESSAGE,
              null,
              available,
              null);
    if (selected != null)
    When the dialog shows, double click one of the items in the JList and then click cancel, the selected will be the item, that's what we unexpected, the null returned will be expected.
    Who can help giving a hint about how to solve this problem?
    PS: One of the solutions is don't call this static method but write our own code or to create a class to extend the JOptionPane, but I think it is ineffective.

    It's a bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6428694

  • Help with JOptionPane.showInputDialog

    Hi!!
    People here helped me before so trying my luck again:)
    In order to get information from people I use JOptionPane.showInputdialog,
    problem is if I need to get 2 different types of info I have to use
            naam = JOptionPane.showInputDialog(null, "Geef speler naam:");
            land = JOptionPane.showInputDialog(null, "Geef Land Speler:");Is there anyway to make this happen in 1 screen?
    Or do I have to make a new frame for that with textfields and such?
    if so, anyone got an example?

    im new here:) so.. New to Java Technology suits me
    well I guess.No it doesn't. New to Java forum is for classpath questions, simple compile time problems and lazy students to cross post their assigments into.
    Swing questions, such as the one you asked, should be asked in the Swing forum because the people who answer questions in there are more knowledgeable about Swing. Plus you will almost 100% likely to find working example codes from previous posts in the Swing forum for Swing related questions.
    Much more likely than in here anyway.

  • LAST QUESTION ABOUT MY CODE (promise)

    Here is my final code for the 6/49 lottery game (it's a more simplified version so don't mind that there is no Bonus Number) sorry for the long code...
    I'll just post my question here for those who don't want to go through all of this.
    I want to throw an exception and let it catch it after the first input box appears. So let's say I entered text or a null value in the first input box then it would loop back to the beginning of the program and output a message saying "You entered a wrong value!"
    But in the code that I have, even if I enter text or just press enter without inputting anything, it just moves on to the next input box, until on the 6th input box it says "invalid value".
    So how would I proceed in doing this?
    THANKS!
    import java.util.Random;
    import javax.swing.*;
    public class Game
         public static void main (String args[])     
              mGame();
         }//end main
         public static void mGame()
              JOptionPane.showMessageDialog(null, "Ali Uz\n110231263", "About", JOptionPane.PLAIN_MESSAGE);
              Random randomNumbers = new Random();
              String sInput,
                      win = "";
              int iNumber1=0,
                   iNumber2=0,
                   iNumber3=0,
                   iNumber4=0,
                   iNumber5=0,
                   iNumber6=0,
                   match=0,
                   randNumber,
                   prize=0;
             int array [] = new int [50];
              try
                        //get the numbers from the user
                        sInput=JOptionPane.showInputDialog ("Enter winning number 1.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 2.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 3.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 4.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 5.");
                        sInput=JOptionPane.showInputDialog ("Enter winning number 6.");
                        //convert strings to integers
                        iNumber1=Integer.parseInt(sInput);
                        iNumber2=Integer.parseInt(sInput);
                        iNumber3=Integer.parseInt(sInput);
                        iNumber4=Integer.parseInt(sInput);
                        iNumber5=Integer.parseInt(sInput);
                        iNumber6=Integer.parseInt(sInput);
             }//end try
              catch (Exception e)
                        System.out.println ("Invalid input please try again");
                        System.exit (0);
              }//end catch
              for (int i=1; i<=6; i++)
                   randNumber = 1 + randomNumbers.nextInt(49);
                   array [randNumber] = randNumber;
                   if (randNumber==iNumber1)
                             match++;
                   else
                             if (randNumber==iNumber2)
                                       match++;
                             else
                                       if (randNumber==iNumber3)
                                                 match++;
                                       else
                                                 if (randNumber==iNumber4)
                                                           match++;
                                                 else
                                                           if (randNumber==iNumber5)
                                                                     match++;
                                                           else
                                                                     if (randNumber==iNumber6)
                                                                               match++;
                   if (match==3)
                        prize = 10;
                        if (match==4)
                             prize = 1000;
                             if (match==5)
                                  prize = 10000;
                                  if (match==6)
                                       prize = 1000000;
              for ( int counter = 1; counter < array.length; counter ++)
                      if (counter % 7 == 0)
                                System.out.printf("%s\n", array [counter]);
                     else
                            System.out.printf("%s ",  array [counter]); 
                   if (match >= 3)
                             System.out.println ("You have gotten " + match + "/6 correct\nYou have won $" + prize);
                   else
                             System.out.println ("You have gotten " + match + "/6 correct\nSorry you have lost! Please try again");     
    }//end class Assignment1

    Your problem here as that the exception you want to
    throw takes place here
    iNumber1=Integer.parseInt(sInput);
    public void showMessage(int number){
    try{
    sInput=JOptionPane.showInputDialog ("Enter
    nter winning number " + number);
    iNumber1=Integer.parseInt(sInput);
    }catch(Exception e){
    System.out.println ("Invalid input please try
    e try again");
    System.exit (0);
    }then call this method from inside a for loop:
    for(int i=1; i <=6; i++){
    showMessage(i);
    }Hope that helps you a littleOnly catch NumberFormatException there, though.

  • Using JOptionPane.showInputDialog to return an integer

    I am currently using JOptionPane to return a string from the Object array i made with all possible choices.
         private static boolean determineService(){
              JLabel label;
              label=new JLabel("Please select which Service Model to use.",JLabel.CENTER);
              Object[] possibilities = {"AddressCleanse", "VIN", "PostalCode"};
              serviceModel = (String)JOptionPane.showInputDialog(
                                  null,
                                  label,
                                  "Select Service",
                                  JOptionPane.PLAIN_MESSAGE,null,
                                  possibilities,
                                  "AddressCleanse");
    //          If a string was returned, say so.
              if ((serviceModel != null) && (serviceModel.length() > 0)) {
                  System.out.println("You've selected " + serviceModel + "!");
                  setVariables();
                  return true;
              }else{
    //               If you're here, the return value was null/empty.
                   System.out.println("Null or Bad service selected!\n Exiting program.");
                   return false;
              }I would like to instead return the response as an integr so I can then use a switch, rather than recursive if, else if logic.
    Apparently java doesnt allow switches to use strings (like PHP does)
    any ideas?

    Just a question more than an answer: would using a hashmap ever work here? where the key is a string and the value is an (???) object that implements an interface that would allow you to call an appropriate method? Perhaps one could use the keySet() and toArray to build the Object array for the JOptionPane. I thought I read something about this somewhere, but am not sure....

  • JOptionPane.showInputDialog and Focus

    I have a program that allows the user to type in a String in a text box and when they hit the enter key the text will appear in a text area. I've also added a menu bar to the program. When the user clicks on File and then Connect from the menu bar I want a JOptionPane to pop up that asks for the user to type in a username and then prompt for a password. And I've gotten all of that to work. Now for the problem. I click on file from the menu bar and then connect and it prompts me for the username as it should. I am able to just type in a phrase in the text field of the username dialog box and hit the enter key and then it prompts me for my password. I am still able to type in a phrase in the text field of the password Dialog box, however when I hit the enter key, the Dialog box does not close as it did for the username Dialog box. It will still close if I click on the OK button, but just pressing the enter key does not close the Dialog box as it did when it prompted for a username. I'm thinking I need to direct the focus to the password dialog box, but not sure how to go about doing this. Any help in solving this problem would be greatly appreciated.
    Here is my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class TestJOptionPane extends JFrame implements ActionListener{
         private static int borderwidth = 570;
         private static int borderheight = 500;
         private JPanel p1 = new JPanel();
         private JMenu m1 = new JMenu("File");
         private JMenuBar mb1 = new JMenuBar();
         private JTextArea ta1 = new JTextArea("");
         private JTextField tf1 =new JTextField();
         private Container pane;
         private static String s1, username, password;
         private JMenuItem [] mia1 = {new JMenuItem("Connect"),new JMenuItem("DisConnect"),
              new JMenuItem("New..."), new JMenuItem ("Open..."), new JMenuItem ("Save"),
              new JMenuItem ("Save As..."), new JMenuItem ("Exit")};
    public TestJOptionPane (){
         pane = this.getContentPane();
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
         dispose();
    System.exit(0);
         setJMenuBar(mb1);
    mb1.add(m1);
    for(int j=0; j<mia1.length; j++){
         m1.add(mia1[j]);
    p1.setLayout( new BorderLayout(0,0));
    setSize(borderwidth, borderheight);
    pane.add(p1);
              p1.add(tf1, BorderLayout.NORTH);
              p1.add(ta1, BorderLayout.CENTER);
              this.show();
              tf1.addActionListener(this);
              for(int j=0; j<mia1.length; j++){
                   mia1[j].addActionListener(this);
         public void actionPerformed(ActionEvent e){
              Object source = e.getSource();
              if(source.equals(mia1 [0])){
                   username = JOptionPane.showInputDialog(pane, "Username");
                   password = JOptionPane.showInputDialog(pane, "Password");
              if(source.equals(tf1)){
                   s1=tf1.getText();
                   ta1.append(s1+"\n");
                   s1="";
                   tf1.setText("");
         public static void main(String args[]){
              TestJOptionPane test= new TestJOptionPane();
    }

    But using JOptionPane doesn't get the focus when you call itworks ok like this
    import javax.swing.*;
    import java.awt.event.*;
    class Testing
      public Testing()
        final JPasswordField pwd = new JPasswordField(10);
        ActionListener al = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            pwd.requestFocusInWindow();}};
        javax.swing.Timer timer = new javax.swing.Timer(250,al);
        timer.setRepeats(false);
        timer.start();
        int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
        if(action < 0)JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected");
        else JOptionPane.showMessageDialog(null,"Your password is "+new String(pwd.getPassword()));
        System.exit(0);
      public static void main(String args[]){new Testing();}
    }

  • JOptionPane.showInputDialog error checking?

    menu = JOptionPane.showInputDialog("What would you like to do next: \n" +
    "1: Enter another person (" + (data.length - index - 1) + " entries left)\n" +
    "2: Display data sorted by First Name\n" +
    "3: Display data sorted by Last Name\n" +
    "4: Display data sorted by Birth Date\n" +
    "5: Search data by First Name\n" +
    "6: Search data by Last Name\n" +
    "7: Search data by Birth Date\n\n" +
    "0: Exit");How can I error check that to make only those values will be entered. I thought I would be able to say something like, if(menu != "0") and so on, but that doesn't seem to work, neither does if(menu == null). Thanks in advance for any help, I am probably just doing something stupid.

    You will get more chance on a suitable answer if you post this Swing related question in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57

  • Question about Linked Lists

    I'm doing an assignment on linked lists and I'm having trouble understanding the insert method. I'm using the one from the book and it works fine, but I don't quite understand it.
    public void insert(Object o) {
    Node n = new Node(o,current);
    if (previous == null)
    head = n;
    else
    previous.next = n;
    current = n;
    It's my understanding that current is the value that your currently at in the list. Previous is equal to the value before the current. So, previous.next is equal to current. This reasoning won't make the list progress with this code. Can someone tell me what I'm not understanding, or explain how this progresses?

    Thanks, that helps alot. Now, I have another question. I need to add and remove nodes from the list. I have it setup where the user can choose what node to delete. It compiles and runs fine, but when I try to delete a node, it doesn't delete it. Doing some troubleshooting, I found that it gets into the for loop, but doesn't do anything with the if/else statement. I put a printline in the if and else part, and it never printed out the statement in the if statement or in the else statement. Here's the code I'm using. getLentgh() is a method I wrote to return an integer value of how many nodes are in the list. I've also tried putting in a printline after the for loop, but still in the try, it didn't print it out.
    else if(source == remove) {
    String del = JOptionPane.showInputDialog("Enter an integer to remove.");
    Node temp = new Node(del,current);
    if(del != null){
    try{
         for(int c = 0; c < list.getLength(); c++){            
         if(temp.data == current.data){
              list.remove();
              c = list.getLength();
         else{
              list.advance();     
    }catch(NullPointerException e){
    }

  • Catch user entry error in JOptionPane.showInputDialog()

    i just want to know if the user entered a String instead of a int...
    i tryed instanceof but didnt worked..
    m_sQuantite = JOptionPane.showInputDialog("How much do you need : " + itmSelect.toString());

    what r u about to ask, what the statement returns.

  • How to put  JPasswordField on JOptionPane.showInputDialog ?

    Hi,
    I want to use "JOptionPane.showInputDialog" and a "JPasswordField" on it.
    How can I put "JPasswordField" on JOptionPane.showInputDialog?
    Here is my code but there is a simple JTextField automatically generated on showInputDialog.
    // JPasswordField pf = new JPasswordField();
    // String str = new String (pf.getPassword());
    String pass = JOptionPane.showInputDialog(null,
                                   "Enter password to access:",
                                   "Demanding Password",
                                   JOptionPane.QUESTION_MESSAGE);I thank you in advance.

    Don't crosspost. This is a Swing related questions and you've already posted the question on the Swing forum.

  • Questions about your new HP Products? HP Expert Day: January 14th, 2015

    Thank you for coming to Expert Day! The event has now concluded.
    To find out about future events, please visit this page.
    On behalf of the Experts, I would like to thank you for coming to the Forum to connect with us.  We hope you will return to the boards to share your experiences, both good and bad.
     We will be holding more of these Expert Days on different topics in the months to come.  We hope to see you then!
     If you still have questions to ask, feel free to post them on the Forum – we always have experts online to help you out.
    So, what is HP Expert Day?
    Expert Day is an online event when HP employees join our Support Forums to answer questions about your HP products. And it’s FREE.
    Ok, how do I get started?
    It’s easy. Come out to the HP Support Forums, post your question, and wait for a response! We’ll have experts online covering our Notebook boards, Desktop boards, Tablet boards, and Printer and all-in-one boards.
    We’ll also be covering the commercial products on the HP Enterprise Business Community. We’ll have experts online covering select boards on the Printing and Digital Imaging and Desktops and Workstations categories.
    What if I need more information?
    For more information and a complete schedule of previous events, check out this post on the forums.
    Is Expert Day an English-only event?
    No. This time we’ll have experts and volunteers online across the globe, answering questions on the English, Simplified Chinese, and Korean forums. Here’s the information:
    Enterprise Business Forum: January 14th 7:00am to 12:00pm and 6:00pm to 11:00pm Pacific Time
    Korean Forum: January 15th 10am to 6pm Korea Time
    Simplified Chinese Forum: January 15th 10am to 6pm China Time
    Looking forward to seeing you on January 14th!
    I am an HP employee.

    My HP, purchased in June 2012, died on Saturday.  I was working in recently installed Photoshop, walked away from my computer to answer the phone and when I came back the screen was blank.  When I turned it on, I got a Windows Error Recovery message.  The computer was locked and wouldn't let me move the arrow keys up or down and hitting f8 didn't do anything. 
    I'm not happy with HP.  Any suggestions?

  • Have questions about your Creative Cloud or Subscription Membership?

    You can find answers to several questions regarding membership to our subscription services.  Please see Membership troubleshooting | Creative Cloud - http://helpx.adobe.com/x-productkb/policy-pricing/membership-subscription-troubleshooting- creative-cloud.html for additional information.  You can find information on such topics as:
    I need help completeing my new purchase or upgrade.
    I want to change the credit card on my account.
    I have a question about my membership price or statement charges.
    I want to change my membership: upgrade, renew, or restart.
    I want to cancel my membership.
    How do I access my account information or change update notifications?

    Branching to new discussion.
    Christym16625842 you are welcome to utilize the process listed in Creative Cloud Help | Install, update, or uninstall apps to install and evaluate the applications included with a Creative Cloud Membership.  The software is fully supported on recent Mac computers.  You can find the system requirements for the Creative Cloud at System requirements | Creative Cloud.

  • Questions about using the Voice Memos app

    I'm currently an Android user, but will be getting an iPhone 6 soon. My most used app is the voice memos app on my Android phone. I have a couple questions about the iPhone's built-in voice memos app.
    -Am I able to transfer my voice memos from my Android phone to my iPhone, so my recordings from my Android app will show up in the iPhone's voice memos app?
    -When exporting voice memos from the iPhone to computer, are recordings in MP3 format? If not, what format are they in?
    -In your opinion, how is the recording quality of the voice memos app?

    You cannot import your Android voice memos to your iPhone's voice memo app.  You might be able to play the Android memos and have the iPhone pick up the audio and record it.
    Here is the writeup about sending voice memos from the iPhone to your computer (from the iPhone User Guide):
    App quality is excellent.

Maybe you are looking for