Focus on JOptionPane

I have a problem.
If I want to change something within a table, a JOptionPane opens, in which i can enter some values.
But if I switch to another program over the task bar while the JOptionPane is still open, and I return to my Java program over the task bar, the main window has the focus and the JOptionPane is hidden. During this, the user has no posibillity to close the program. The only possibility to get the JOptionPane back is by ALT+TAB!
Is it possible, that the JOptionPane will over the task bar?

Just to easy, that it is really embarassing:
JOptionPane.showMessageDialog(frame,"Message");
The first parameter is the parent container. If you pass your main frame, it is modal and in front of the frame!

Similar Messages

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

  • Focus on JOptionPane - how?

    hi.
    in my program, when the user enters an incorrect input, i simply call JOptionPane.showMessageDialog to display an error message. I'd like for the focus to shift to the error window, so that the user can simply hit ENTER to make it go away, rather than having to tab over to the window.
    oddly, when the window pops up, focus remains on the main program window. is there a simple way to make the focus shift to the new window?
    i'm using swing to do all my gui stuff.
    thanx in advance.
    ~spoongirl

    You are wanting to make the dialog box modal. The answer on how to do this is contained:
    http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html

  • 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 en default focus issues

    Hello,
    I have written a simple class to show a login dialog, but I can't get the default focus right. My problem is that I want the first JTextField (usernameField) to be the one select when my dialog shows, but I want the first button (Ok button) to be called automatically when I press enter. What happens now that I set the first button (Ok button) default (last argument of JOptionPane.showOptionDialog), this makes sure that whenever I press enter this buttons gets called en the dialog reacts accordingly. But when the dialog is first shown this default button is also the one selected (having focus), this is not what I want. The JTextField (usernameField) should be selected (have focus) so a user can enter his username, then press enter and see what happens.
    When I don't set a default button nothings happens when I press enter but now the right JTextFields (usernameField) is selected.
    Hope anyone can help me.
    Thank you very much.
    The code:
    public class LoginDialog
        private int attempts;
        private TargetFinder controller;
        private Component parent;
        private String username;
        private String password;
        public LoginDialog(TargetFinder controller, Component parent)
            this.controller = controller;
            this.parent = parent;
            username = "";
            password = "";
        private int buildDialog()
            String dialogTitle, usernameText, passwordText, errorPart1, errorPart2;
            String[] buttonsText;
            try
                dialogTitle = LanguageParser.getText("loginTitle");
                usernameText = LanguageParser.getText("username");
                passwordText = LanguageParser.getText("password");
                buttonsText = new String[2];            
                buttonsText[0] = LanguageParser.getText("loginTitle");
                buttonsText[1] = LanguageParser.getText("cancel");
                errorPart1 = LanguageParser.getText("loginError1");     
                errorPart2 = LanguageParser.getText("loginError2");
            catch (Exception e)
                throw new RuntimeException("Login dialog could not be created", e);
            JPanel namePanel = new JPanel(false);
            namePanel.setLayout( new GridLayout(0, 1) );
            namePanel.add( new JLabel(usernameText) );
            namePanel.add( new JLabel(passwordText) );
            JPanel fieldPanel = new JPanel(false);
            fieldPanel.setLayout( new GridLayout(0, 1) );
            JTextField usernameField = new JTextField(12);
            fieldPanel.add(usernameField);
            JPasswordField passwordField = new JPasswordField(12);
            fieldPanel.add(passwordField);
            JPanel componentPanel = new JPanel(false);
            componentPanel.setLayout( new BoxLayout(componentPanel,
                    BoxLayout.X_AXIS) );       
            componentPanel.add(namePanel);
            componentPanel.add(fieldPanel);
            JPanel componentPanelError = new JPanel(false);
            componentPanelError.setLayout( new GridLayout(0, 1) );
            componentPanelError.add(componentPanel);
            JLabel errorLabel = new JLabel(
                    "<html>" +
                    errorPart1 +
                    "<br>" +
                    errorPart2 +
                    "</html>" );   
            errorLabel.setForeground(Color.RED);
            componentPanelError.add(errorLabel);
            int res;
            res = JOptionPane.showOptionDialog(
                    parent,
                    (attempts == 0) ? componentPanel : componentPanelError,
                    dialogTitle,
                    JOptionPane.OK_CANCEL_OPTION,
                    (attempts == 0) ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE,
                    null,
                    buttonsText,
                    buttonsText[0] );
            if (res == JOptionPane.OK_OPTION)
                username = usernameField.getText();
                password = new String( passwordField.getPassword() );
            return res;
        public boolean login()
            attempts = 0;
            Database database = controller.getDatabase();
            while ( buildDialog() == JOptionPane.OK_OPTION )
                if ( database.login(username, password) )
                    return true;
                attempts++;
            return false;
    }

    Thanks for your reaction Olek,
    But I can't request focus because JOptionPane creates a model window, so the JVM waits for the user to click one of the buttons.
    Also I don't know how to add a ButtonListers to any of the buttons because the are created dynamicly by JOptionPane.
    I use JOptionPane.OK_CANCEL_OPTION to create both an Ok and a Cancel button, and define an array (buttonsText) with names for them. I can't ask the rootPane for this buttons because they only excist after I call JOptionPane.showOptionDialog(...) and this is model window.
            int res;
            res = JOptionPane.showOptionDialog(
                    parent,
                    (attempts == 0) ? componentPanel : componentPanelError,
                    dialogTitle,
                    JOptionPane.OK_CANCEL_OPTION,
                    (attempts == 0) ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE,
                    null,
                    buttonsText,
                    buttonsText[0] );With kind regards,
    Eddy

  • Focus problem when JPopupMenu is shown

    I have compiled and ran the following 'JPopupTest.java' in JDK 1.4.1 on Windows. Kindly conduct the two tests as given below
    First Test :
    ============
    The class shows an editable JComboBox and a JButton when visible. Now click the down-arrow button of the JComboBox and make the drop-down popup visible. Then click on the "OK" button while the popup is visible. The popup gets hidden and a dialog is displayed as it should be.
    Second Test :
    =============
    Run the appilcation again. This time type something in the editable textfield of the JComboBox. A custom JPopupMenu with the text "Hello World" would be visible. Then click on the "OK" button while the popup is visible. The expected dialog is not shown. The custom JPopupMenu gets hidden. Now click on "OK" button again. The dialog is visible now.
    My Desire :
    ===========
    When I click on the "OK" button in the "Second Test" the JPopupMenu should get hidden and the dialog gets displayed (as it happens for the "First Test") in one click.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    import java.util.*;
    public class JPopupTest extends JPanel implements DocumentListener, ActionListener
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         JPopupMenu jpopupmenu;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         public JPopupTest()
            vec = new Vector();
               vec.addElement("One");
            vec.addElement("Two");
            vec.addElement("Three");
            vec.addElement("Four");
            vec.addElement("Five");
            vec.addElement("Six");
            vec.addElement("Seven");
            vec.addElement("Eight");
            vec.addElement("Nine");
            vec.addElement("Ten");
            jcombobox = new JComboBox(vec);
            jcombobox.setEditable(true);
            _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
            jtextfield = ((JTextField) _bcbe.getEditorComponent());
            jtextfield.getDocument().addDocumentListener(this);
            add(jcombobox);
            button = new JButton("OK");
            button.addActionListener(this);
            add(button);
            jpopupmenu = new JPopupMenu();
            jpopupmenu.add("Hello World");
         public void insertUpdate(DocumentEvent e)  {changedUpdate(e);}
         public void removeUpdate(DocumentEvent e)  {changedUpdate(e);}
            public void changedUpdate(DocumentEvent e)
            if(!jpopupmenu.isVisible())
            jpopupmenu.show(jcombobox, 0, jcombobox.getHeight());
            jtextfield.requestFocus();
         public void actionPerformed(ActionEvent e)
            JOptionPane.showMessageDialog(this, "OK button was pressed");
         public static void main(String[] args)
            JPopupTest test = new JPopupTest();
            JFrame jframe = new JFrame();
            jframe.getContentPane().add(test);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jframe.setSize(200,100);
            jframe.setVisible(true);

    See the code below with auto complete of text. When button is pressed, still TF gets focus after JOptionPane dialog is closed.
    -Pratap
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    public class JPopupTest extends JPanel implements ActionListener {
         JButton button;
         Vector vec;
         JComboBox jcombobox;
         BasicComboBoxEditor _bcbe;
         JTextField jtextfield;
         MyComboUI comboUi = new MyComboUI();
         public JPopupTest() {
              vec = new Vector();
              vec.addElement("One");
              vec.addElement("Two");
              vec.addElement("Three");
              vec.addElement("Four");
              vec.addElement("Five");
              vec.addElement("Six");
              vec.addElement("Seven");
              vec.addElement("Eight");
              vec.addElement("Nine");
              vec.addElement("Ten");
              jcombobox = new JComboBox(vec);
              jcombobox.setEditable(true);
              jcombobox.setUI(comboUi);
              add(jcombobox);
              button = new JButton("OK");
              button.addActionListener(this);
              add(button);
              _bcbe = ((BasicComboBoxEditor) jcombobox.getEditor());
              jtextfield = ((JTextField) _bcbe.getEditorComponent());
              jtextfield.addCaretListener(new CaretListener() {
                        public void caretUpdate(CaretEvent e) {
                             if (!jcombobox.isPopupVisible() && jtextfield.isShowing() &&
                                       jtextfield.hasFocus()) {
                                  jcombobox.showPopup();
                             String text = jtextfield.getText().toLowerCase();
                             int index = -1;
                             for (int i = 0; i < jcombobox.getItemCount(); i++) {
                                  String item = ((String) jcombobox.getItemAt(i)).toLowerCase();
                                  if (item.startsWith(text)) {
                                       index = i;
                                       break;
                             if (index != -1) {
                                  comboUi.getList().setSelectedIndex(index);
                             } else {
                                  comboUi.getList().clearSelection();
                   jtextfield.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent e) {
                             if (e.getKeyCode() == e.VK_ENTER) {
                                  Object value = comboUi.getList().getSelectedValue();
                                  jcombobox.setSelectedItem(value);
                                  jcombobox.hidePopup();
         public void actionPerformed(ActionEvent e) {
              JOptionPane.showMessageDialog(this,"OK button was pressed");
              jtextfield.requestFocus();
         public static void main(String[] args) {
              JPopupTest test = new JPopupTest();
              JFrame jframe = new JFrame();
              jframe.getContentPane().add(test);
              jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jframe.setSize(200,100);
              jframe.setVisible(true);
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList() {
                   return listBox;

  • JOptionPane event blocking problem

    Hi,
    JOptionPane is causing me a problem.
    I have a simple frame that contains a text field and a button.
    Pressing the button should write something to the standard output.
    When the text field loses focus a JOptionPane in poped to the user.
    The following scenario is problematic:
    1. The text field owns the focus.
    2. The user presses the button.
    Expected result:
    The JOptionPane appears due to the lost focus event on the text field.
    After closing it some text is written to the standard output due to the action event on the button.
    The actual result:
    The JOptionPane does appears but after closing it nothing is written to the standard output. The button stays in a curious state (when the mouse hovers over the button the button looks pressed, and when the mouse doesn't hover over the button the button looks unpressed).
    Probable reason for this behaviour:
    The JOptionPane blocks all awt/swing events while it is opened. Some of the button code is perfomed due to the button press, but the ActionListener's actionPerformed method is not invoked.
    I need the actionPerfomed method to be invoked.
    Can anyone help me?
    Here is the source code:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    public Test() {
    public static void main(String[] args) {
    //Test test1 = new Test();
    final JFrame f = new JFrame("Test");
    JButton b = new JButton("Click Here");
    JTextField tField = new JTextField("Text", 10);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("Button pressed!");
    tField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    if (e.isTemporary()) return;
    JOptionPane.showMessageDialog(f,
    "Focus lost",
    "Title",
    JOptionPane.INFORMATION_MESSAGE);
    JPanel content = (JPanel)f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
    content.add(tField);
    content.add(Box.createHorizontalStrut(5));
    content.add(b);
    f.pack();
    f.show();
    Thanks,
    Shai

    Hello Shai.
    The JOptionPane seems to consume all events when its shown. (Check the stack after JOptionPane is shown.) I've solved a similar problem with the SwingUtilities.invokeLater() method. Maybe the following example will help:
    Runnable doDlgError = new Runnable() {
    public void run() {
    JOptionPane.showMessageDialog(this, "Error", "Error",
    JOptionPane.ERROR_MESSAGE);
    SwingUtilities.invokeLater(doDlgError);
    -Olaf

  • Avoiding key ENTER to "click" OK Button

    I have a JDialog with a Canvas inside. I have to handle the keyboard event generated when user presses ENTER in order to write somethig in the Canvas. My event listener is able to handle it. The problem is that the dialog's OK button receives the event too and the dialog is closed as if the user has clicked on it.
    What could I do?

    Thank you guys, but your solutions have not worked.
    When the user presses ENTER, the OK Button is "clicked" even when it doesn't have the focus. JOptionPane creates this button as the "active" one and I don't know how to avoid this behavior.
    I've already tried this:
    pane = new JOptionPane(...);
    JRootPane root = pane.getRootPane();
    root.setDefaultButton(null);
    It hasn't worked ... NullPointerException in that third line.
    And when I tried to getRootPane after creating the Dialog, the setDefaultButton(null) had no effect.
    Any other ideas?

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

  • How to set focus in the parent window after a JOptionPane pop up ?

    I am not able to set the focus back to a JTextField in the parent window after poping up a JOptionpane.showMessageDialog(). I tried requestfocus(),requestFocusInWindow etc......but not working. The code is given below.
    if ((encryptor.encrypt(password)).equals(configuredPasswd)) {
                        validPassword = true;
                   } else {
                        JOptionPane.showMessageDialog(saveUI,"The password entered is not correct.");
                        saveUI.getPasswdField().setText("");
    saveUI.getPasswdField().requestFocus();
    Sometimes the focus is coming to the JTextField.Sometimes it appears for a moment and then dissappears.Please give a solution

    see if this makes a difference
    if((encryptor.encrypt(password)).equals(configuredPasswd))
      validPassword = true;
    else
      JOptionPane.showMessageDialog(saveUI,"The password entered is not correct.");
      ActionListener al = new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          saveUI.getPasswdField().setText("");
          saveUI.getPasswdField().requestFocusInWindow();}};
      javax.swing.Timer timer = new javax.swing.Timer(100,al);
      timer.setRepeats(false);
      timer.start();
    }

  • How to create an YES/NO JOptionPane with the default focus on No?

    Hi,
    can somebody please show me how to display an JOptionPane with the options Yes and No that has the focus by default no the No button?
    By default it is on the Yes button which is rather problematic for confirm dialogs like "Do you really want to delete everything?".
    JPJava

    It would help if JPJava gave some sample code SSCCE to show they know how to construct a JOptionPane
    I use explorer to access the source files in the zip folder and JGrasp to view the source code
    this is copy modify from the API
    Object[] options = { "YES", "CANCEL" };//{"OK", "CANCEL"} shown in api
    JOptionPane.showOptionDialog(null, "Are you sure you want to delete", "Confirm Delete",
    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    null, options, options[1]);//options[1] selects CANCEL option as defaultthis method constructs
    showOptionDialog
    public static int showOptionDialog(Component parentComponent,
                                       Object message,
                                       String title,
                                       int optionType,
                                       int messageType,
                                       Icon icon,
                                       Object[] options,
                                       Object initialValue)
                                throws HeadlessExceptionBrings up a dialog with a specified icon, where the initial
    choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.
    If optionType is YES_NO_OPTION, or YES_NO_CANCEL_OPTION and the options parameter is null,
    then the options are supplied by the look and feel.
    The messageType parameter is primarily used to supply a default icon from the look and feel.
    Parameters:
    parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent
    has no Frame, a default Frame is used
    message - the Object to display
    title - the title string for the dialog
    optionType - an integer designating the options available on the dialog: YES_NO_OPTION, or
    YES_NO_CANCEL_OPTION
    messageType - an integer designating the kind of message this is, primarily used to determine the icon from
    the pluggable Look and Feel: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
    QUESTION_MESSAGE, or PLAIN_MESSAGE
    icon - the icon to display in the dialog
    options - an array of objects indicating the possible choices the user can make; if the objects are components,
    they are rendered properly; non-String objects are rendered using their toString methods; if this parameter is null,
    the options are determined by the Look and Feel
    initialValue - the object that represents the default selection for the dialog; only meaningful if options is used; can be null
    Returns:
    an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog
    Throws:
    HeadlessException - if GraphicsEnvironment.isHeadless returns true
    See Also:
    GraphicsEnvironment.isHeadless()Edited by: Ross_M on Sep 22, 2008 9:19 AM

  • Change the initial focus to "message" in JOptionPane.showOptionDialog?

    JPanel panel = new JPanel (false);
    JTextArea txtArea = new JTextArea (msg, 2, 60);
    JScrollPane sPane = new JScrollPane (txtArea);
    panel.add (sPane);
    int button = JOptionPane.showOptionDialog (frame, panel, titleStr, optionType, JOptionPane.PLAIN_MESSAGE, null, null, null);
    Is there a way to make txtArea to have the initial focus?
    Thanks,
    Ben

    Hi,
    Check out this post:
    Hide the 'no data found' message
    I hope that helps.
    -Marc

  • JOptionPane and Focus

    Hello All,
    I've got a small problem with setting the focus in a JOptionPane. My JOptionPane consists of one JComboBox and two JTextFields. I've created this JOptionPane by putting the components in an array and passing it to the JOptionPane constructor. Initially it starts with the focus on the top most component (the JComboBox). What i would like is to have it focussed on one of the JTextFields.
    Does anyone have any idea how to do this?
    Thanks in advance.

    Don't use a JOptionPane, why not use a modal JDialog? That way it is much easier to organise the components and arrange focus

  • How to focus No button in JOptionPane.showConfirmDialog?

    How to focus No button in JOptionPane.showConfirmDialog when the Dialog window is opened?
    (default it focus Yes button).
    Please help me. Thank you very much.

    Use the showOptionDialog(...) method then you can specify the buttons and which button has focus.

  • JOptionPane loosing focus

    I have the following piece of code. The problem is after I say YES to the first JOptionPane, the second JOptionPane displayed doesn't have focus. I'm displaying both the JOptionPane on JPanel. Can someone help me out and tell how can I get the focus on to the second JOptionPane ?
    public static boolean deleteConfirm(Component parent, String title, String confirmMsg1, String confirmMsg2) {
         int response = -1;
         response = JOptionPane.showOptionDialog(parent,                               confirmMsg1, title, JOptionPane.DEFAULT_OPTION,      JOptionPane.WARNING_MESSAGE, null, YES, NO);
         if(response == 0) {
    response = JOptionPane.showOptionDialog(parent,                               confirmMsg2, title, JOptionPane.DEFAULT_OPTION,                     JOptionPane.WARNING_MESSAGE, null, YES, NO);
         if(response == 1) return true;
         return false;

    This test worked just fine:
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame {
    public Test() {
         setSize(200,200);
         show();
         boolean b = deleteConfirm(this, "Please confirm", "Do you really want to delete", "Are you really really sure?");
    public static boolean deleteConfirm(Component parent, String title, String confirmMsg1, String confirmMsg2) {
    int response = -1;
    response = JOptionPane.showConfirmDialog(parent, confirmMsg1, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
    if(response == 0) {
         response = JOptionPane.showConfirmDialog(parent, confirmMsg2, title, JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
         if(response == 1) return true;
    return false;
    public static void main(String args[]) {
         Test t = new Test();
    }Note that I used showConfirmDialog() instead of showOptionDialog().
    Save it to Test.java, compile and run.

Maybe you are looking for

  • Calling normal java web service from bpel

    hi, i want to call a normal java web service (which has been deployed in an application server) and not a bpel process from my .bpel file. i see that while creating a partner link , i have to specify the wsdl file location. there are two options. fro

  • Data on phone lost when updating software

    I have a 3gs - when i get prompted by itunes to update software my phone freezes after the process and I get locked onto the insert usb cable screen. I have to restore to last setting to get it going again which takes hours. can you help please. late

  • Final Cut HD produced video stops halfway on dvd player

    So, I'm having an issue that I have never experienced. The movies that I have edited on Final Cut HD and burned on IDVD seem to stop half way on my dvd player. I've edited three different movies and they all seem to stop half way on the dvd player or

  • Working with Frames | Learn InDesign CS6 | Adobe TV

    Everything that is placed into InDesign ends up in a frame. You can create frames from scratch, or if you "place" (import) text or images into a document, InDesign automatically creates the frame for you. We'll explore the use of frames in InDesign i

  • Windows 7 license expired

    We had already activated windows 7 professional 32 bit. Second day it show windows expired need to activate . No services we can start or stop. mainly antivirus scep we cannot update definition. how to resolve the issue ramdas dhavade