JOptionPane.showConfirmDialog()+grab focus

Hi
How do I get the cursor blinking in the textfield of JOptionPane.showConfirmDialog() by default when my code executes JOptionPane.showConfirmDialog() ?
Thanks
apoorva

Hi Apoorva,
Here I am giving you working code. This cocmpletely solves your problem.
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
public class test extends JFrame {
     private static final long serialVersionUID = 1L;
     private JPanel jContentPane = null;
     private JButton jButton = null;
     private JPasswordField tPasswordField;
      * This method initializes jButton     
      * @return javax.swing.JButton     
     private JButton getJButton() {
          if (jButton == null) {
               jButton = new JButton();
               jButton.setBounds(new Rectangle(85, 121, 104, 27));
               jButton.setText("Click");
               jButton.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                         System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
//                         JPasswordField tPasswordField = new JPasswordField(
                         tPasswordField = new JPasswordField(10);
                         tPasswordField.setEchoChar('*');
                         SwingUtilities.invokeLater(new Runnable()
                            public void run()
                                   tPasswordField.requestFocus();
                         int ret=JOptionPane.showConfirmDialog(test.this,
                                   tPasswordField,
                                   "Enter server password",
                                   JOptionPane.OK_OPTION);
          return jButton;
      * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    test thisClass = new test();
                    thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    thisClass.setVisible(true);
      * This is the default constructor
     public test() {
          super();
          initialize();
      * This method initializes this
      * @return void
     private void initialize() {
          this.setSize(300, 200);
          this.setContentPane(getJContentPane());
          this.setTitle("JFrame");
      * This method initializes jContentPane
      * @return javax.swing.JPanel
     private JPanel getJContentPane() {
          if (jContentPane == null) {
               jContentPane = new JPanel();
               jContentPane.setLayout(null);
               jContentPane.add(getJButton(), null);
          return jContentPane;
}Now u can mark this as fixed and assign duke stars.. :-)

Similar Messages

  • 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.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.showConfirmDialog: Tabbing between options creates wrong result

    In JOptionPane.showConfirmDialog, when pressing <tab> to move between options and then pressing <Enter> I always get a returned zero (0) no matter which button is in focus. Is this a (known) bug or am I stupid?
    I run the following code.
    import javax.swing.*;
    public class TabOptions
    public static void main (String [] args)
         int n = JOptionPane.showConfirmDialog (null, "Use <Tab> to shift option-button, then press <Enter>. " +
                             "I'll write the returned value to sdt out.");
         System.out.println ("Returned value: " + n);
    }

    import javax.swing.*;
    class TabOptions
    public static void main (String [] args)
    UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);//<--------------------
    int n = JOptionPane.showConfirmDialog (null, "Use <Tab> to shift option-button, then press <Enter>. " +
    "I'll write the returned value to sdt out.");
    System.out.println ("Returned value: " + n);
    }

  • JOptionPane.showConfirmDialog  "NO" button acting as "YES" on MAC using TAB

    JOptionPane.showConfirmDialog "NO" button acting as "YES" on MAC using TAB

    Ya , I am asking question ? Why "NO" is acting as "YES" button in case of JOptionPane.showConfirmDialog on MAC using TAB.
    i.e,
    I clicked on some button, then showConfirmDialog is opened, By default the focus is on "YES" button. Now I pressed TAB button and changed to the focus to "NO" button.
    If press ENTER key --> acting "YES"
    If press SPACE key -> acting as "NO"
    Why ?
    What should I do to make it correct ?
    Am I need mention set (Key,value) pairs for UIManager in case of MAC.
    Please suggest ?

  • JOptionPane.showConfirmDialog requires two key strokes with Java SE 6.

    I have been using the following line of code:
    rc = JOptionPane.showConfirmDialog( comp, objects, "Warning",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.INFORMATION_MESSAGE);
    with no problems with plug-in 1.4 and 1.5. Now with 1.6, when I choose Yes/No/Cancel, the first time I press the button nothing happens, the second time I press the button the action takes place.
    I have been searching for information on this and have not found any known issues (yet). Does anyone have any ideas?

    further investigation shows that this only happens when the component is a JComboBox. I found a new bug that seems to be the same issue:
    http://bugs.sun.com./bugdatabase/view_bug.do?bug_id=6817939
    When calling JOptionPane.showConfirmDialog from an ActionListener called by a JComboBox, there is 2 issues:
    * the focus is not given to the confirm dialog

  • JOptionPane.showConfirmDialog() displays weird msg

    I use showConfirmDialog() to request whether or not the program should continue when SUBMIT button is pressed. The first time the button is pressed there are 2 messages displayed in the dialog box: a fake one followed by the real one. This behaviour is not observed if the button is pressed a second time.
    This is only noticeable if I connect to the server where it runs using X windows. The same code run on either a LINUX PC or connecting to server using telnet doesn't show this behaviour.
    Partial code
    public void actionPerformed(ActionEvent ae) {
    String msg = new String("Do you really want to submit this list?");
    String dtitle = new String("Pls. choose one :)");
    int msgType = JOptionPane.QUESTION_MESSAGE;
    int optionType = JOptionPane.YES_NO_OPTION;
    if (ae.getSource() instanceof JButton && ae.getActionCommand().equals("SUBMIT")) {
    jbtn.setBackground(Color.red);
    // Confirm dialog
    int r = JOptionPane.showConfirmDialog((Component)this,msg,dtitle,optionType,msgType,null);
    Thks

    Hi m8, thanks got that working......sometimes you just cant see whats stareing you in the face!!
    Just one more thing...i have used your code to display the confirmdialog...but is there any way i
    can set the default focus to the textfield when the JOptionPane is made?
    Thanks again

  • JOptionPane.showConfirmDialog

    Hi there,
    I have a confirm dialog that i want to close whenever the [x] is clicked in the top left of the window, but i just keep getting a error.
    I have made a custom confirm dialog that i have added a object to that allows user input.
    I had to do this since I couldnt find out if the OK or Cancel button was pressed on the default one!.
    CODE so FAR....
    Object[] msg = {
    "Please Enter a valid Guess (3-27)", textField};
    result = JOptionPane.showConfirmDialog(null, msg, title,
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.PLAIN_MESSAGE);

    Hi m8, thanks got that working......sometimes you just cant see whats stareing you in the face!!
    Just one more thing...i have used your code to display the confirmdialog...but is there any way i
    can set the default focus to the textfield when the JOptionPane is made?
    Thanks again

  • Problem w/JOptionPane showConfirmDialog

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

  • JOptionPane.showConfirmDialog -- remember decision checkbox

    Hi
    JOptionPane.showConfirmDialog -- remember decision checkbox
    is there something to set "remember my decision" for the following dialog box i.e. this dialog sits inside a loop over a set of files
    so if i say "yes overwrite" it should remember that decision. Should i make a dialog box on my own or is there a parameter setting for this
    purpose ?
    if(currentCsvOutputFile.isFile()){
    int userConfirm = JOptionPane.showConfirmDialog(
              new JFrame(),
              currentCsvOutputFile + " already exists , Do you want to overwrite it ? " ,
              "Confirm",
              JOptionPane.YES_NO_OPTION);
    }Regards

    No need for a custom dialog, just add a JLabel and a JCheckBox to a JPanel and pass that as the message parameter.JCheckBox remember = new JCheckBox("Remember my decision");
        JPanel panel = new JPanel(new BorderLayout()); // or whatever layout you find best
        panel.add(new JLabel("File already exists , Do you want to overwrite it ? "), BorderLayout.NORTH);
        anel.add(remember, BorderLayout.SOUTH);
        int userConfirm = JOptionPane.showConfirmDialog(new JFrame(), panel, "Confirm", JOptionPane.YES_NO_OPTION);db

  • Deploy; JDev grabs focus back when done.

    Is there any way to make JDEV not grab focus back when a deployment is complete?
    ISSUE: A deployment takes minutes. I use my PC to do other things while deployment ( and compiling ) is going on... like email, write on this board, etc.
    I can do this without performance pain cuz I'm running a dual processor.
    While I'm busy typing away JDEV suddenly completes the deployment, grabs focus.. and stuff I'm typing furiously into email gets dropped into wherever the cursor was last sitting in the JDEV source editor!
    For that matter, I've had deployments fail when I'm doing other things... If I deploy and do NOTHING on that PC while deployment is occurring.. it happily completes.
    My only course at the moment is to sit and stare at the screen during deployments.. twiddling my fingers ( no JDEV manuals to read through off my shelf grin ). I'm almost to the point where I need a second computer to avoid losing an hour a day of "work" outside of JDEV.
    JDEV isn't the only critter who does this sorta thing, but it'd be nice if it shared the sandbox more politely.

    Yes, there is a way to do this:
    1) Select your deployment profile.
    2) Right click and select "Properties..."
    3) Go to the "Project" tab.
    4) Click the "Advanced..." button.
    5) Under the "General" tab, UNCHECK "Redirect messages to the message view".
    This will cause messages to be accumulated in a text area that is within the modal dialog. Once you dismiss the dialog you will no longer have access to the deployment messages that were produced. But, JDeveloper will not steal the focus back when deployment finishes in this case, because that dialog stays up until you explicitly close it.
    Concerning your second issue with deployment failing while you're doing something else, can you provide additional details on what kind of deployment profile you are deploying, how you invoke deployment, and what the failure messages are?
    Hope this helps.
    --joj (JDeveloper Deployment)
    null

  • JOptionPane.showConfirmDialog in Russian

    I have an application that supports many languages including Russian. All other texts are displayed in Russian language correctly. However, I have an issue with JOptionPane.showConfirmDialog() in Russian language. This issue does not occur in ZH or ES. Does anyone know why the JOptionPane.showConfirmDialog() show the Yes/No button in English while the locale is in Russian? How can I fix this issue?
    Thanks!

    Does anyone know why the JOptionPane.showConfirmDialog() show the Yes/No button in English while the locale is in Russian?Tried to track it down, but gave up. So I (still) have no idea.
    How can I fix this issue?Here's one way:import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    public class RussianDialog {
      public static void main(String[] args) {
        UIManager.put("OptionPane.yesButtonText", "&#1044;&#1072;");
        UIManager.put("OptionPane.noButtonText", "&#1053;&#1077;&#1090;");
        UIManager.put("OptionPane.cancelButtonText", "&#1086;&#1090;&#1084;&#1077;&#1085;&#1080;&#1090;&#1100;");
        JOptionPane.showConfirmDialog(null,
                "&#1088;&#1091;&#1089;&#1089;&#1082;&#1080;&#1081;", "&#1088;&#1091;&#1089;&#1089;&#1082;&#1080;&#1081;".toUpperCase(),
                JOptionPane.YES_NO_CANCEL_OPTION);
    }Note that you will need to compile usingjavac -encoding UTF8 RussianDialog.javaif your default encoding doesn't support the Russian characters.
    db

  • Firefox won't stay minimized. Keeps restoring and grabbing focus.

    I have firefox minimized while I work. Every so often, the firefox window is restored and grabs focus.
    Very annoying!
    Windows 7 x64

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode
    *https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • JOptionPane.showConfirmDialog in servlets

    Hi
    I am trying to show a dialog in a doPost method of a servlet. For some reason, it blocks the entire method and does not show the dialog. What gets me voiceless is that it works in the doGet method of the servlet.
    The situation is the following:
    - a first serlvet dispatches GET requests to other servlets according to the role of users.
    - in the doGet of this first servlet, a second (servlet2) is instantiated and its doGet is called;
    - in the doGet of servlet2, a HTML form (POST method) is generated;
    - when the submit button of the HTML form is pressed, the form is processed by the doPost of servlet2.
    JOptionPane.showConfirmDialog works in servlet2 only in the doGet and not in the doPost. Their code is:
    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataModule1 dm = (DataModule1) ixPageProducer1.getSessionDataModule(request.getSession());
    dm.parameterRow1.setString("empl_ini", request.getRemoteUser());
    dm.queryDataSet1.refresh();
    empl_id = dm.queryDataSet1.getInt("number");
    ixPageProducer1.servletGet(this, request, response);
    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataModule1 dm = (DataModule1) ixPageProducer1.getSessionDataModule(request.getSession());
    dm.queryDataSetReq.insertRow(false);
    ixPageProducer1.servletPost(this, request, response);
    JOptionPane.showConfirmDialog(null, "test" , "Request Confirmation", JOptionPane.YES_NO_OPTION);
    (I am using JBuilder and its InternetBeans to link the HTML pages with the DB).
    Many thanks in advance for helping a desperate Java beginner!!!

    I figured out that the dialog was actually generated, but "behind" my browser.You can try this to add the following either before or after the JOptionPane.showConfirmDialog:
    JOptionPane.requestFocus();
    But I think your best bet is to associate a frame with your dialog box as follows:
    Object parent = this.getParent();
    while (!(parent instanceof Frame)) parent = ((Component)parent).getParent();
    F = (Frame)parent;
    JOptionPane.showConfirmDialog(F, "test" , "Request Confirmation", JOptionPane.YES_NO_OPTION);
    If this helps, don't forget the Dukes
    ;o)
    V.V.

  • Prevent notify-send from grabbing focus in xmonad

    I just started using xmonad, and I've got most of the wrinkles ironed out, but this one still bugs me. I use pidgin + libnotify, and whenever a notification pops up, it grabs focus, meaning I can't type anything for a minute (unless I move my mouse and close it). This is particularly annoying when I'm having a chat back-and-forth, and I get notifications from that window/another chat window.
    (I know I can turn off the notifications when the window is currently open, but it doesn't solve the larger problem of notifications grabbing focus when I'm typing in a separate screen).

    That was not a conscious choice; I just switched from xfce, so that makes sense.
    I uninstalled xfce4-notifyd, installed notification-daemon, and reinstalled pidgin-libnotify (for good measure). The notifications still work, so I'm assuming notification-daemon is working properly, but the focus still gets grabbed.
    Do you use pidgin as well, or just notification-daemon? I still get the same issue when I do notify-send, which makes me believe it's not pidgin's problem, but maybe not.
    This website seems to imply that it's an xmonad configuration issue, but I'm not that familiar with Haskell/xmonad's configurations. Is it possible to alter this behavior *only* for notify-send events, but not anything else that might display an urgent window?

Maybe you are looking for

  • No audio on One-Step DVD in iDVD

    Just recently I have been tranfering VHS to mini-DV tape and then going straight to DVD using the OneStep DVD method. I have never had a problem until recently. Now when I do that, there is no audio on the final product. Any solutions out there?

  • Distinct Count Function-how to use properly

    Hello, I am new to using forums & have only been using Crystal since May of 2009, so i hope i do this correctly & provide the appropriate information.  i've looked for this answer in what's been posted but cannot find it.  Some things i've read I don

  • Exchange Rate in MIGO ( IMPORT)

    Dear Experts, As per requirment we need our MIGO account entries (Import) should be store with Exchange Rate which we maintained in OB08 with our Bill of entry date not posting date . Means if our Bill of entry date is 29.12.2011 and exchange rate 50

  • Macbook Pro w/Retina - Horizontal Lines on Entire Display

    We have just issued some 15" MacBookPros with Retina Displays to users. They are running Yosemite. Users are complaining about very low contrast horizontal lines that run the entire width of the screen across all windows, including the background des

  • SQLPlus: Spool is wrapping lines at 80 chars when linesize = 1000

    I have following code and the result wrap off at 80 . Please suggest ways to avoid it. Thanks set define on set echo off set pages 10000 set heading off set lines 1000 set long 10000 set heading on set feedback off set heading off set verify off set