JOptionPane.showInputDialog without CANCEL Button

How can I do a JOptionPane.showInputDialog without CANCEL Button.
Besides if I press OK without tyoing anything, will a null String but returned?
Thanks

I don't think you can with an Input Dialog. Normally, you want to give the user a chance to cancel the operation. Here is an example using a Message Dialog. After the user hits OK, you can get the text from the text field.          JPanel p = new JPanel(new GridLayout(2,1));
          JTextField t = new JTextField();
          JLabel l = new JLabel("A message");
          p.add(l);
          p.add(t);
          JOptionPane.showMessageDialog(null,p,"Title",JOptionPane.PLAIN_MESSAGE);

Similar Messages

  • Cancel button weird problem

    im trying to program a game that works with JOptionPane, and ive come to this weird problem:
    this works fine but throws a null pointer exeption when i press the cancel button:
    if (e.getSource() == easy)     {
    do {
         word = JOptionPane.showInputDialog (x.create(1));
    result = "" + ((x.right(word)) ? "YOU GUESSED!" : "YOU MISSED!");
    JOptionPane.showMessageDialog (null, result);
    while (palabra != null);
    but when i try to catch the exeption:
    if (e.getSource() == easy)     {
    try {
    do
         word = JOptionPane.showInputDialog (x.create(1));
    result = "" + ((x.right(word)) ? "YOU GUESSED!" : "YOU MISSED!");
    JOptionPane.showMessageDialog (null, result);
    while (word != null);
    catch (NullPointerException no){}
    The weird thing happens:
    the first time i press cancel it works fine but if i press easy again and then cancel it just reloads the input dialog and if i press cancel again it works, but if i do easy again, this time i have to press cancel 4 times for it to work, and if i press easy again i need 8 cancel, then 16 and so on....
    i have no idea why this happens....
    can anybody give me some help?
    thank you.

    /* the error takes place when presing the cancel button
         to make this work press "press me first" and then activate me will show the
         window, presing cancel and then again activate me makes everithing worse */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class sample     {
    static JButton neu = new JButton("Press Me!");
    JButton act = new JButton("Activate Me!");
    String word,result;
    public Component createComponents() {
    neu.setMnemonic('i');
    neu.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         act.addActionListener(this);
    if (e.getSource() == act)     {
            do
             word = JOptionPane.showInputDialog ("press cancel");
             result = "" + ((word.equals("cancel")) ? "yes!" : "cancel!!!");
             JOptionPane.showMessageDialog (null, result);
            while (word != null);
         JPanel pane = new JPanel();
            pane.setLayout(new GridLayout(0, 10));
         pane.add(act);
         return pane;
    public static void addComponentsToPane(Container newbie) {
    newbie.setLayout(new GridLayout(5,5,5,5));
    newbie.add(neu);
    private static void createAndShowGUI() {
            JFrame frame = new JFrame("Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            addComponentsToPane(frame.getContentPane());
            frame.pack();
            frame.setVisible(true);
    public static void main(String[] args) {
    try {                              
                UIManager.setLookAndFeel(
                    UIManager.getCrossPlatformLookAndFeelClassName());
            } catch (Exception e) { }
    JFrame frame = new JFrame("LETTERAMA");
            sample app = new sample();
            Component contents = app.createComponents();
            frame.getContentPane().add(contents, BorderLayout.CENTER);
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
          frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
           frame.pack();
            frame.setVisible(true);
    //ps. sorry for the horrible grids, i was kind of in a hurry

  • Processing Page with cancel button.

    Hi,
    I have implement Processing Page but client wants to have cancel button to cancel the process.
    Can anyone give suggestions how to implement this?
    SC

    My requirement is that i have a custom base page with submit button. When user clicks on submit button it would start long running process
    And I should show a dialog page with clock saying process in progress message and a cancel button. User should be able to stop the process by clicking cancel button and back to base page. OAF gives the processing page that i want but without cancel button.
    I try to add cancel button on the processing page programmatically but while it is processing and when i click on cancel button i cannot capture the event.
    how to add cancel button on it and capture event? Is this correct approach?
    Can any body could suggest the best approach and solution?
    Thanks
    SC

  • JOptionPane.showInputDialog and the cancel button

    so i'm using a JOptionPane.showInputDialog, and everything works except when i click the cancel button to exit the window, it gives me an error.
    how can i remedy this?
    here's a section of my code: (a is an array, as is b)
    firstWord = JOptionPane.showInputDialog
    ("What company's sloagan is/was: "+a[count]+"?");
    if(firstWord.equalsIgnoreCase(b[count]))
    JOptionPane.showMessageDialog (null,
    "Thats Right, the company was "+b[count]+".");
    count++;
    int YesNo = JOptionPane.showConfirmDialog (null,
    "Do you want to play again?", "Choose One", JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
    if(YesNo==1) //this should exit out if you click no
    System.exit (0);
    if(count==10)
    JOptionPane.showMessageDialog(null,
    "Game Over. You Won.");
    System.exit (0);
    else
    JOptionPane.showMessageDialog (null,
    "Sorry, you aren't that smart. Guess again.");
    }]

    1- Seems like you misstyped your code tags...
    2- When you say: "it gives me an error", please provide details (e.g. stack trace)
    3- Read the API doc, it says: showInputDialog returns user's input, or null meaning the user canceled the input.
    So firstWord.equalsIgnoreCase(b[count]) will throw a NullPointerException in that case.
    You might check for null value.
    Note:str1.equals(str2) will throw a NullPointerException when str1 is null, but str2 can be null without a NullPointerException being thrown:String str1 = null;
    String str2 = "toto";
    System.out.println(str1.equals(str2)); // NullPointerException
    System.out.println(str2.equals(str1)); // ok (prints false)

  • How to use the cancel button in showInputDialog

    um how would i go with overriding the cancel button's deafult function in JOptionPane.showInputDialog?
    in my code:
    package alphaOne;
    * this program takes in a number and gets the factorial of that number
    import javax.swing.*;
    public class Factorial {
         public Factorial() {
               * variables intilization, input is where the option pane puts the data
               * number is teh actucal number entered parsed from string result is
               * where the resutl is stored flag1 is the indicator if the user had
               * entered an integer
              String input;
              int flag1 = 0;
              int number = 0;
              long result = 0;
               * this while loop runs continously unless an integer is entered
              while (flag1 != 1)
                   try {
                        input = JOptionPane
                                  .showInputDialog("Enter the number to be factored, Integer only: ");
                        number = Integer.parseInt(input);
                        flag1 = 1;
                   } catch (NumberFormatException ea) {
                        JOptionPane.showMessageDialog(null,
                                  "The input was not a integer!", "Warning",
                                  JOptionPane.ERROR_MESSAGE);
              result = number;
              for (int x = 1; x < number; x++) {
                   result = result * (x);
              JOptionPane.showMessageDialog(null, "The result is: " + result,
                        "Result", JOptionPane.CLOSED_OPTION);
              try {
                   System.exit(0);
              } catch (SecurityException ea) {
                   System.out.print("ARRRRR its dead!");
         public static void main(String[] args) {
              Factorial One = new Factorial();
    }the cancel button does not break the while loop

    what is the value of null compared to when you compare it, and do we use the String.equals() or the String == null to compare? as seen in here i tried with input.equals(null) as a comparison but it deos not exit when i press cancel
    package alphaOne;
    * this program takes in a number and gets the factorial of that number
    import javax.swing.*;
    public class Factorial {
         public Factorial() {
               * variables intilization, input is where the option pane puts the data
               * number is teh actucal number entered parsed from string result is
               * where the resutl is stored flag1 is the indicator if the user had
               * entered an integer
              String input;
              boolean flag1 = false;
              int number = 0;
              long result = 0;
               * this while loop runs continously unless an integer is entered
              while (flag1 != true){
                   try {
                        input = JOptionPane
                                  .showInputDialog("Enter the number to be factored, Integer only: ");
                        number = Integer.parseInt(input);
                        System.out.println(input);
                        flag1 = true;
                        if (input.equals(null))
                             try {
                                  System.exit(0);
                             } catch (SecurityException ea) {
                                  System.out.print("ARRRRR its dead!");
                   } catch (NumberFormatException ea) {
                        JOptionPane.showMessageDialog(null,
                                  "The input was not a integer!", "Warning",
                                  JOptionPane.ERROR_MESSAGE);
              result = number;
              for (int x = 1; x < number; x++) {
                   result = result * (x);
              JOptionPane.showMessageDialog(null, "The result is: " + result,
                        "Result", JOptionPane.INFORMATION_MESSAGE);
              try {
                   System.exit(0);
              } catch (SecurityException ea) {
                   System.out.print("ARRRRR its dead!");
         public static void main(String[] args) {
              Factorial One = new Factorial();
    }i have also tried to ue input == null, input == "", input.equals(""), input.equals(" ")
    Message was edited by:
    TheHolyLancer
    i edited the part so it is bold
    Message was edited by:
    TheHolyLancer

  • JOptionPane.showInputDialog cancel brings up a blank box

    String name = JOptionPane.showInputDialog(
        null,
        "My message",
        "My title",
        null,
        null,
        null)  // real list of options deleted for brevityThis works okay, but when I press the cancel button, I get a blank warning JOptionPane (message box thingy)... how do I tailor the message in that? Been looking through the search results and API with little luck.

    handle it like so
    try
        String s = new JOptionPane.showInputDialog(null, "Enter input");
    catch(Exception ee)
        JOptionPane.showMessageDialog("Invalid input");
    }

  • JOptionPane showInputDialog Buttons

    hi
    I want to remove the cancel button from the showInputDialog? Is it possible
    Here is my code.
    String sRoleSelect = (String) JOptionPane.showInputDialog(frame, "Please Select Role",
    "dialog", JOptionPane.ERROR_MESSAGE, icon, rolelist
    .toArray(), 1);
    Thanks

    i created JOptionPane and customized to remove the buttons.

  • Creating a dialog box with OK and Cancel buttons without OADialogPage

    Hi Experts,
    i want to create a dialog box for Delete Confirmation means after clicking on delete it should pop up a small dialog box with OK/Cancel buttons
    and need code for the same to handle the buttons.
    i have created with OADialogPage but its showing in a complete page but i want to show those buttons in a small box.
    Plz help.
    THANKS IN ADVANCE.
    Thanks
    Raja.

    Hi,
    I have not tried using javascript in destination URI as suggested by Mukul.
    I have tried the below code for opening a page as dialog box.
    You can try it for your requirement by creating a dialog page of your own, say XXDialogPage (with OK and Cancel button)
    StringBuffer l_buffer = new StringBuffer();
    l_buffer.append("javascript:mywin = openWindow(top, '");
    String url = "/OA_HTML/OA.jsp?page=/xx/oracle/apps/fnd/dialog/webui/OADialogPG";
    OAUrl popupUrl = new OAUrl(url, OAWebBeanConstants.ADD_BREAD_CRUMB_SAVE );
    String strUrl = popupUrl.createURL(pageContext);
    l_buffer.append(strUrl.toString());
    l_buffer.append("', 'lovWindow', {width:500, height:500},false,'dialog',null);");
    pageContext.putJavaScriptFunction("SomeName",l_buffer.toString());
    In dialog page's controller, you can forward it to the page onc ethe user selects OK or Cancel.
    Pass the selected value back to the main page and further you can use it for deleting.
    Regards.

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

  • Input dialog question OK/Cancel Button

    Hi there,
    I�m busy with an application that displays an input dialog box on start up. It prompts the user for their name. This imput will then be used for a JLabel welcoming the user with their name. If no name is entered. The Jlabel will display �Welcone User�. Everythng works fine but when I press cancel on the input dialog box I get an error. Below is some code of what I�ve done so far.
    Thanks,
    Patrick.
    String name = JOptionPane.showInputDialog(null,
              "Please enter your name",
              "Name input",
              JOptionPane.PLAIN_MESSAGE);
              welcome = new JLabel(name);
              if (name.length() == 0) {
                   welcome = new JLabel("Welcome User");
              else if (name.length() > 0) {
                   welcome = new JLabel("Welcome " + name);

    The error is NullPointerException.
    If the cancel button is pushed a null is returned.
    Try this test instead
    if ((name == null) || (name.length() == 0))
       welcome = new JLabel("Welcome User");
    }

  • Cancel button help

    hi
    im still fairly new to java and i was just wondering how i would go about making a cancel button for my JOptionPane boxes
    also i have an array that when its searched it displays the result in JOptionPane windows, but if there are more than one result it will show it up in one then another one comes up after and displays in there to. i want them both displayed in the same box
    part of my coding is here:
    if (inputbox == 1){
    String input2 = JOptionPane.showInputDialog("Please enter a flight number eg QF5");
    for (int row = 0; row < 21; row++) {
      if (Flights[row][0].equals(input2)){
              JOptionPane.showMessageDialog(null,"flight " + Flights[row][0] + '\n'  + "Will be leaving from " + Flights[row][3] + " and going to " + Flights[row][4] + '\n' + "Departing at: " + Flights[row][1] + " And will arrive at: " + Flights[row][2]);
    }code]
    i use a menu system at the start which they press a number, in this example its 1, it will take them to another box that askes them to enter a flight number which it then searches the array for. it works ok if there is only one answer but if there is more than 1 then it shows them in seperate boxes, i want them in the same box.
    thank you for your time
    cheers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    no offence but I have great difficulty reading your posts they contain very little punctuation making them hard to read were you to take a little more care I'd help but I can't be arsed to read it six times to figure out what you're on about thanks have a nice day

  • JOptionPane.showInputDialog Help!!!!

    Hello,
    I'm using JOptionPane.showInputDialog(Component parentComponent,
    Object message,
    String title,
    int messageType,
    Icon icon,
    Object[] selectionValues,
    Object initialSelectionValue ).
    which prompts the user to add some text and the same will be stored for later retrieval.
    In this case, JOptionPane pops up with a label, textfield,OK & Cancel buttons.
    Default focus is given to to the TextField.
    Is there anyway to get access to the TextField via code ?
    For example, if the user types "Hello World" in the given TextField, then I need to get the Text entered in
    the TextField in the following manner.
    String myStr = myJOptionPaneTextField().getText();
    System.out.println("Entered Text is "+ myStr);
    How can I Achieve the same ?
    Thanks in advance
    Regards
    vargav

    Why? At what point do you know you should manipulate the text? Usually, it would be when the user clicks OK, at which point it doesn't matter because the dialog is dismissed. So what kind of operations do you expect to be able to do?
    Aside from that, I'm not sure how to get the text field in the option pane, per se... It can be gotten by digging thru the pane's components til you find a text field. But you'd need to do that in a separate thread. So it's not really feasible to do that.... There is an alternative:
    The message is an object, and it can be an array of objects, which will all be added, and thus can include a message string and a text field...
    JTextField myfield = new JTextField();
    Object[] obj = new Object[2];
    obj[0] = "Enter some text here:";
    obj[1] = myfield;
    if(JOptionPane.showOptionDialog(obj, "Enter Text", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
       String value = myfield.getText();
    }Then you can do whatever you want with the text field... but the same problem is there, you have lost the dialog before you can do anything.

  • How to customize JOptionPane.showInputDialog?

    Is there a way to change the text on the ok- and cancel buttons in the JOptionPane.showInputDialog()?
    I'm trying to make the input dialog display Norwegian text in the OK and Cancel buttons, but it seems impossible...?
    None of the JOptionPane.showInputDialog methods take the options-array as input, and none of the JOptionPane constructors let me create a input dialog.
    Does anyone know how this can be done, or do I have to write my own InputDialog?

    You can get a partial list of the properties from the UIDefaults Hashtable returned by UIManager.getDefaults(), but for the rest you have to look at the source code. For example, I got this from the source code of BasicOptionPaneUI.          } else if (type == JOptionPane.OK_CANCEL_OPTION) {
                        defaultOptions = new ButtonFactory[2];
                        defaultOptions[0] = new ButtonFactory(
                            UIManager.getString("OptionPane.okButtonText",l),
                            getMnemonic("OptionPane.okButtonMnemonic", l),
                            (Icon)DefaultLookup.get(optionPane, this,
                                              "OptionPane.okIcon"), minimumWidth);
                        defaultOptions[1] = new ButtonFactory(
                            UIManager.getString("OptionPane.cancelButtonText",l),
                            getMnemonic("OptionPane.cancelButtonMnemonic", l),
                            (Icon)DefaultLookup.get(optionPane, this,
                                              "OptionPane.cancelIcon"), minimumWidth);db

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

  • Af:dialog model-restore / cancel-button processing best practice ?

    Using JDev 11.1.1.3; if I have an af:dialog running in an af:popup which contains auto-submit components (for cross-component enablement, validation etc.). My question is what are the preferred ways of discarding the model submitted changes made through popup processing if/when the af:dialog cancel button is pressed by user ? Figured that using a task flow for the content that is the popup could be an option, and using the task flow savepoint restore feature, but that looks more like database restore than model restore. I want to be able to restore the model content to the way it looked before the popup executed, without necessitating a submit to the database. How is this most commonly and best achieved ?
    Thanks,

    Taskflow savepoints are not database savepoints. Transactional BTF can be configured to issue automatic savepoints at TF entry and eventually to "rollback" to them at the TF exit. The internal implementation uses the ApplicationModule's passivation/activation mechanism to passivate the AM state at the TF entry and eventually to activate the AM state at the TF exit back to the passivated state at the entry. In this way it is simulated that you have not made any modifications in ADF BC, so your model layer will be restored to the state before TF entry. (Of course, you must not perform any DB commits durring the lifetime of this TF). I have used successfully this mechanism for the same goal you are asking about.
    Also there are savepoints managed by the ADF Controller, but I could be of little help here because I have never used them. I suspect that this mechanism could be what you need, so you may have a look here for more details:
    Adding Save Points to a Task Flow
    and in this thread:
    {thread:id=2128956}
    Dimitar

Maybe you are looking for

  • DBMS_LOB and memory management

    Hello all, When I declare a CLOB variable (myclob) do I always have to free it with dbms_lob.freetemporary(myclob) at the end of my procedure ? I know I have to free it if it was created with dbms.createtemporary(myclob,....) but what happens when I

  • Incoming call not working

    Hello Guys, I have an issue with the incoming calls. We I dial the 10 digitss number using my Cell phone, it doesn't go through. I receive a message stating "the call can't go through". But we can call from inside to outside and within the company. A

  • How to change 'Wait for condition' period?

    Hi all     I am using a workflow with a 'wait for condition' step in it. It takes so long to wait, how I reduce the waiting time?     I think it should be a periodly job in background to check the condition, but I don't know which one it is~

  • SharePoint 2010 : Slider webpart

    Hi techies, I got a requirement to implement slider webpart in SharePoint2010 and i created slider webpart by using BXslider plugin here is the Screenshot: <script type="text/javascript" src="/_layouts/Scripts/jquery-1.11.0.min.js"></script> <script

  • Discovery web services in java uddi registry via php-pear

    I have published my web service in java uddi registry and I want to discovery this web services via php-pear. The pear code has not the setting about this uddi registry. The pear code for IBM and Microsoft registries are: 'IBM' => array( 'Inquiry' =>