Home / Java Patterns and Pitfalls     frequal.com

Fixing JOptionPane Focus Issues


Commonly with a JOptionPane you want the first JTextField to have the focus. Unfortunately, the JOptionPane implementation for the most-commonly-used convenience methods puts the focus in the "OK" button. The key is to use the convenience methods that take an array of button labels. Then the focus goes in your first custom component, which is usually what you want.


Instead of this:
  JTextField txfName = new JTextField();
  // Don't do this!  The focus will go in the OK button
  int result = JOptionPane.showConfirmDialog(null, txfName, "Enter a name", JOptionPane.OK_CANCEL_OPTION);
Do this:
  JTextField txfName = new JTextField();
  // By passing a list of option strings (and a default of null), the focus goes in your custom component
  String[] options = {"OK", "Cancel"};
  int result = JOptionPane.showOptionDialog(null, txfName, "Enter a name", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, null);
The JTextField will have the focus.
Last modified on 28 Jul 2010 by AO

Copyright © 2016 Andrew Oliver