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.

Similar Messages

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

  • 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

  • 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 cant see displayed message

    I need some help.
    In my program i try to display a JOptionPane.showInputDialog(f,"Save file as ","save as",JOptionPane.QUESTION_MESSAGE);
    The JOptionPane displays but I can't see the message text and the textfield does not display until I write something in the window?
    Whats wrong, How can I fix it?
    Please help me!

    Well I tried it out, and it works on my machine.
    Try compiling this:
    import javax.swing.*;
    public class JForumTester
    extends Object
         public static void main(String[] args)
              JOptionPane.showInputDialog(null,"Save file as ","save as",JOptionPane.QUESTION_MESSAGE);
              System.exit(0);
    to see if it's the dialog that's the problem or something else.
    //Java Rules!
    --RXon
    PS; if you e-mail me, be sure to put the word "JDNForum" at the end, so it doesn't get caught in my spam guard;

  • 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 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

  • Setting focus in JOptionPane.showInputDialog

    Hi!
    For usability I want to set the focus to the dialog that pops up if i call JOptionPane.showInputDialog(...).
    Someone an idea how this works?
    cu

    Hi...
    I am facing exactly the same problem... If you have found a solution, please contact me at:
    [email protected]
    Regards.

  • Custom icon for JOptionPane.showInputDialog

    As a novice who's wading through Deitel's 'Java how to program', using java2 and j2sdk1.4.1 on JCreator Pro. I want to use my own icons on a small proggie i've written. I know that the format is:
    showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
    however this doesn't tell me how to write the code. how do i change the default '?' icon for my own icon?
    thanks for any help
    rgds
    adambi

    This should help you also
                ImageIcon ico = new ImageIcon("drag2.jpeg");
                Frame frame = new Frame();
                Object[] options = {"Yes, please",
                        "No, thanks",
                        "No eggs, no ham!"};
              JOptionPane.showInputDialog(frame,
              "What some eggs ?.",
              "My title",JOptionPane.ERROR_MESSAGE,ico,options,
        options[2]);also here is a good link for ya on dialogs
    http://java.sun.com/j2se/1.4/docs/api/
    GOOD LUCK

  • 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

  • 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.

  • 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.

  • 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)

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

  • JOptionPane.showInputDialog with JTextarea?

    Hi,
    is it possible to put a JTextArea into a JOptionPane.showInputDialog?
    the reason i need to know is because my string is to long to fit into the current JOptionPane.showInputDialog.
    Greeting
    Grad_

    You could use your favorite component in other showXxxDialogs than the showInputDialog. Get the input on the component in an ActionListener or other appropriate event handler you've written for that component.

Maybe you are looking for