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.

Similar Messages

  • How to set focus on JOptionPane

    Hello guys,
    I create a
    String options[] = {"Ok", "Cancle"};
    JOptionPane.showOptionDialog(..,..,..,YES_NO,null,options, JTextField);
    and inside this JOptionPane, there is a JTextField for receive what user input,
    when I set this JTextField to be the default focus, the Ok and cancle button don't receive
    action from Enter key, they are accepted only Mouse-clicked action.
    Do you have another idea to make the button can accept the action from Enter key?

    thank you, but I forgot to tell you that my JTextField is JPasswordField.
    And we can't add keylistener to String, can we?
    this is my code:
    JTextField acodeField = new JPasswordField(12);
    String[] buttonLabels = {"OK","Cancel"};
    do
    acodeField.setText("");
    option = pane.showOptionDialog(this,
    panel,
    super.getTitle(),
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.PLAIN_MESSAGE,
    null,
    buttonLabels,
    acodeField);
    // Quit operation if cancel button is selected.
    if (option != 0 || option < 0) {
    return option;
    } while (authCode.compareTo(acodeField.getText()) != 0);

  • 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 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 with a JList?

    Is there any quick and easy way to use the JOptionPane.showInputDialog with a JList? the default is a drop down menu. Thanks!

    Is there any quick and easy way to use the
    JOptionPane.showInputDialog with a JList? the default
    is a drop down menu. Thanks!I have found a way to this. You need to write your own JOptionPane
    class MyJOptionPane
        public static Object showListInputDialog(Component parentComponent, Object message, String title, Object[] selecttionValues)
            Object defaultOptionPaneUI = UIManager.get("OptionPaneUI");
            UIManager.put("OptionPaneUI", "MyBasicOptionPaneUI");
            Object object = JOptionPane.showInputDialog(parentComponent, message, title, JOptionPane.PLAIN_MESSAGE, null,
                    selecttionValues, selecttionValues[0]);
            UIManager.put("OptionPaneUI", defaultOptionPaneUI);
            return object;
    }And then create your own MyBasicOptionPaneUI extending from javax.swing.plaf.basic.BasicOptionPaneUI with 2 methods overridden. The codes are copied from javax.swing.plaf.basic.BasicOptionPaneUI and modified to get rid of JComboBox.
    public class MyBasicOptionPaneUI extends BasicOptionPaneUI
        public MyBasicOptionPaneUI()
            super();
        public static ComponentUI createUI(JComponent x) {
             return new MyBasicOptionPaneUI();
        protected Object getMessage()
            inputComponent = null;
            if (optionPane != null) {
                if (optionPane.getWantsInput()) {
                    /* Create a user component to capture the input. If the
                       selectionValues are non null  with any size ,
                       it'll be a list, otherwise it'll be a textfield. */
                    Object message = optionPane.getMessage();
                    Object[] sValues = optionPane.getSelectionValues();
                    Object inputValue = optionPane
                            .getInitialSelectionValue();
                    JComponent toAdd;
                    if (sValues != null) {
                            JList list = new JList(sValues);
                            JScrollPane sp = new JScrollPane(list);
                            list.setVisibleRowCount(10);
                            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                            if (inputValue != null)
                                list.setSelectedValue(inputValue, true);
                            list.addMouseListener(new ListSelectionListener());
                            toAdd = sp;
                            inputComponent = list;
                    } else {
                        MultiplexingTextField tf = new MultiplexingTextField(20);
                        tf.setKeyStrokes(new KeyStroke[]{
                            KeyStroke.getKeyStroke("ENTER")});
                        if (inputValue != null) {
                            String inputString = inputValue.toString();
                            tf.setText(inputString);
                            tf.setSelectionStart(0);
                            tf.setSelectionEnd(inputString.length());
                        tf.addActionListener(new TextFieldActionListener());
                        toAdd = inputComponent = tf;
                    Object[] newMessage;
                    if (message == null) {
                        newMessage = new Object[1];
                        newMessage[0] = toAdd;
                    } else {
                        newMessage = new Object[2];
                        newMessage[0] = message;
                        newMessage[1] = toAdd;
                    return newMessage;
                return optionPane.getMessage();
            return null;
        private static class MultiplexingTextField extends JTextField
            private KeyStroke[] strokes;
            MultiplexingTextField(int cols)
                super(cols);
             * Sets the KeyStrokes that will be additional processed for
             * ancestor bindings.
            void setKeyStrokes(KeyStroke[] strokes)
                this.strokes = strokes;
            protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                                int condition, boolean pressed)
                boolean processed = super.processKeyBinding(ks, e, condition,
                        pressed);
                if (processed && condition != JComponent.WHEN_IN_FOCUSED_WINDOW) {
                    for (int counter = strokes.length - 1; counter >= 0;
                         counter--) {
                        if (strokes[counter].equals(ks)) {
                            // Returning false will allow further processing
                            // of the bindings, eg our parent Containers will get a
                            // crack at them.
                            return false;
                return processed;
        private class ListSelectionListener extends MouseAdapter
            public void mousePressed(MouseEvent e)
                if (e.getClickCount() == 2) {
                    JList list = (JList) e.getSource();
                    int index = list.locationToIndex(e.getPoint());
                    optionPane.setInputValue(list.getModel().getElementAt(index));
        private class TextFieldActionListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                optionPane.setInputValue(((JTextField) e.getSource()).getText());
    }

  • Setting focus on a component from backing bean

    Is there an easy way to set focus in a specific component on the jspx from a method in the backing bean? (other than javaScript coding...)

    Hi,
    did you take a look at
    About control the cursor position in a JSF web page
    It contains some links to other weblogs. The links are helpfull. Maybe you'll be able to find your solution there......
    Good luck
    Luc Bors

  • How to set focus on a input field in a selected row of a table?

    In a previous discussion (http://scn.sap.com/thread/3564789) I asked how to access an input (sap.m.Input) field of a selected row in a table. In the answer that was supplied I was shown how to get the items of the table. Then using the selected index to get the selected item get the cells. Then I could set editable on the proper cell(s). This worked fine.
    Now I need to set the focus on one of the fields. I tried something like this:
                var oNewLink = table.getSelectedItem();
                var oNewLinkName = oNewLink.getCells()[1];
                oNewLinkName.focus();
    But this doesn't seem to work.
    I have searched through other discussions and have seen this technique for putting focus on a field if you have its ID:
    sap.ui.getCore().byId(id_of_the_input_field).$().focus();
    In my case though I do not have an ID since the row and its cells are generated. How can I set focus on the cell of a certain row in a table?

    Hello Venkatesh. Yes that code does work. First I tried it on a table cell that was already rendered and it did work. The next time I tried it on a table row that was being added and it did not work there. So I added an on after rendering function for the table and added that code there. That did not work until I added a delay (timeout) to do a context switch before calling the focus and that worked.
    Once last thing though sometimes when I call focus on an input field (actually in a table row cell) if the field has text in it already the flashing cursor is at the beginning of the text and other times it is at the end of the text (which is the desired way). It depends on where I click in the row. Is there anyway to make sure the flashing cursor is at the end of the text when the focus is applied to a field that contains text?

  • How to set focus on the title of JTabbedPane

    I have created a JTabbedPane and added three JPanels to it. They are titled, say "Panel 1", "Panel 2" and "Panel 3". And each of them contains buttons and text areas. Since this app is for physically disabled users, it must provide navigation through these three tabs with keyboard operations only (i.e. without mouse clicks).
    When the title "Panel 1" gets focused, users can go to "Panel 2" by the right arrow key. When Panel 2 is brought up, however, the title "Panel 2" does not get focused. Instead the first button inside panel 2 is focused. In order for users to navigate to 'Panel 3" by the arrow key, the title "Panel 2" has to be focused. How do I set focus on the tab title?
    I have tried 'requestFocus()' on Panel 2, but it does not work. Please help me with this issue. Thanks in advance.

    I'd be quite interested to know if this can be doen as well so I thought I'd post this message to move it to the top of the board.
    Thanks.

  • How to set focus on a custom PO Item screen field when in error?

    Hi All,
    I have an interesting situation that i'm wondering if others have solved.  We have extended the PO item table (EKPO) by adding two new fields.  We then have implemented two BAdI's:  ME_GUI_PO_CUST and ME_PROCESS_PO_CUST to add them to the ME21N/ME22N/ME23N screens and logic to do some validation, via these respective BAdI's mentioned.  Everything works perfectly - with one small issue.  When we are doing some validation via a method on the ME_PROCESS_PO_CUST - and "invalidate" the field (and throw an error) when it is in error - I also want to be able to "set focus" on the field in question (basically: go to the particular tab on the ME* screen and highlight the field).  I have tried using SET CURSOR FIELD *****  within this BAdI (ME_PROCESS_PO_CUST) - but doesn't seem to work.  Has anyone tried to do this and have come up with a solution?  Would be much appreciative if you shared it!!!  Thanks much.
    Cheers,
    Matt
    ERP version that we have is:  ECC 6.0

    Just have a look at oss note 310154 - ME21N/ME51N: Customer-specific check, generating error log.
    In short:
    Add your error messages in EXIT_SAPMM06E_012 (using specific macros).
    Sample code (provided in Oss note) :
      loop at tekpo where knttp eq 'X'.
        loop at tekkn where ebeln eq tekpo-ebeln and
                            ebelp eq tekpo-ebelp and
                            kostl eq space.
          if not tekkn-id is initial.
            mmpur_business_obj_id tekkn-id.
            mmpur_metafield MMMFD_ACCOUNTINGS.
          endif.
          mmpur_message_forced 'E' 'ZE' '777' '' '' '' ''.
        endloop.
      endloop.

  • Back again - set focus

    Hi again,
    I've been struggling with setting focus on each instance of a field within a repeating subform. My subform is limited to 5 instances. Min of 1.
    As the user exits the only textfield in the subform, I have a new instance creating. I want the focus set to the new instance but I have not been able to get anything to work. My latest attempt has been to try to pass a count using the instancemanager to a variable in the setfocus string.
    Here is what I have thus far. I know I need to resolve the node but that process is confusing the heck out of me. I've read and re-read everything I've been able to find but I havent been able to wrap my head around that part successfully.
    Can anyone point me in the correct direction or suggest a better solutions? TIA!
    form1.Account_Client_Information.Long_Title.Account_Long_Title::exit - (JavaScript, client)
    var oSubform = xfa.resolveNode("Long_Title");
    var oNewInstance = oSubform.instanceManager.addInstance(1);
    xfa.form.recalculate(1);
    var count = (this.instanceManager.count)
    xfa.host.messageBox("Text Field Index in new Subform: " + count);
    var vfocindex = xfa.resolveNode("Account_Long_Title[count]");
    xfa.host.setFocus(vfocindex);

    Hi,
    The addInstance method will return the subform that you want so you only need to do;
    var oNewInstance = Subform1.instanceManager.addInstance(1);
    xfa.host.setFocus(oNewInstance.Account_Long_Title)
    Regards
    Bruce

  • How to set focus in text box at server side

    Hi,
    I have small problem , i have a text box in form , which is get validated at server side in servlet , if it found some thing wrong then it throws exception , i want that when an exception is thrown it should set focus for that perticular text box. so what should i write to perform such a activity.

    Get hold of the element ID in the servlet (and keep the code conventions) and print it out to some Javascript function which does a focus during the onload.
    There's an example of focus/highlight using JSP/Servlet/Javascript in this article: [http://balusc.blogspot.com/2008/07/dao-tutorial-use-in-jspservlet.html]. Also see the screenshots at the very bottom.

  • Setting focus in a PDF form

    Hi,
    I'm trying to move a cursor to a particular field based on certain conditions using JavaScript. The method I am using is xfa.host.setFocus("fldTest"); in the initialize event. For some reason the focus isn't getting set to fldTest, but when I first hit tab it goes into the first field that is in the tab order. Is there any way around this?
    Thanks,
    Chad

    You might want to check the reference path of the field that you want to set focus on.
    Ex: xfa.host.setFocus("form1.page1.subform1.TextField1");

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

  • 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

Maybe you are looking for

  • How to get the data from a cluster table to BW

    Dear All, I want to extract the data from R/3 to BW by using 2 tables and one Cluster B2. Actually my report contains some fields from PA2001, PA2002 and one cluster table B2 (Table ZES). Can I create View by using these 3 tables? If it is not possib

  • How do i connect 5.1 speakers to my macbook pro?

    Hey, so I got a pair of logitec X540 speakers the other day, and they have three cords that I need to connect to my computer, but we only get the headphoe jack. Ho do I make them work? Thanks

  • WRT54G v1.1 and buffalo Linkstation problems.. help needed

    Hi there, I have a wrt45G with dhcp running and working. Connecting the linkstation out of the box has no effect. Connecting the linkstation directy to the laptop works fine. I changed the config to a fixed IP outside of the DHCP range, but withing t

  • Hide link to iTunes Store...

    I cannot stand the link in iTunes next to an Artist, Album, Song Name, etc.. So I just downloaded the new iTunes and went to hide it like usual. But it was not in the preferences like usual and that is what the iTunes help said. It's not an option. D

  • Vertical Lines on the on top and bottom of MacBook case.

    Here is a picture of the problem. https://cms.psu.edu/AngelUploads/Files/djb376/macBookCaseLines.JPG What would be a recommendation for cleaning these lines off of the case. I have tried a dampened microfiber cleaning cloth, with no such luck in clea