setFocus in JOptionPane :)

Hey!

I have a JOptionPane that shows a list of items with JList.

I'd like a user to be able to hit the arrow keys to move up/down the list, but the OK button steals focus!

I naturally can't set focus to the JList after the dialog is open... what can I do?

The following is my code, but OK still takes focus:

privatestaticfinalint PLN_MSG = JOptionPane.PLAIN_MESSAGE;

publicstatic Object showListDialog(Component parent, java.util.List<?> o){

JDialog dialog;

final JList list =new JList(o.toArray());

Object[] msg ={"Select an item" +":",new JScrollPane(list)};

final JOptionPane op =new JOptionPane(msg, PLN_MSG, JOptionPane.OK_CANCEL_OPTION,null);

dialog = op.createDialog(parent, (String)msg[0]);

list.setSelectedIndex(0);

list.setCellRenderer(new ListRenderer());

list.addMouseListener(new MouseAdapter(){

publicvoid mouseClicked(MouseEvent e){

if(e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2){

op.setValue(JOptionPane.OK_OPTION);

SwingUtilities.getWindowAncestor(e.getComponent()).setVisible(false);

}

}

});

/** WORKS!!! ADDED CODE */

dialog.addWindowListener(new WindowAdapter(){

publicvoid windowOpened(WindowEvent e){

list.requestFocusInWindow();

}

});

/** WORKS!!! ADDED CODE */

// list.requestFocus(); // Doesn't work here :(

dialog.setVisible(true);

// list.requestFocus(); // Doesn't work here :(

if (((Integer)op.getValue()).equals(JOptionPane.OK_OPTION))

return list.getSelectedValue();

returnnull;

}

Thanks!!!

-Tres

[3108 byte] By [FBLa] at [2007-11-27 8:12:24]
# 1
Got it! See added code. (Added a windowlistener to the dialog that sets focus.)-Tres
FBLa at 2007-7-12 19:56:45 > top of Java-index,Desktop,Core GUI APIs...