我有一个 JComboBox 设置为可编辑,我希望用户能够在按下回车键后跳转到下一个控件。我尝试了很多方法,但都没有奏效,其中一个事件被成功触发(EditorCompoment.keyRelease)但是方法“transferFocus()”并没有像它应该的那样将焦点转移到下一个控件。任何帮助深表感谢。谢谢
public static void addEnterKeyListener(final javax.swing.JComboBox field)
{
field.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
field.setFocusTraversalKeysEnabled(false);
Action myAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
field.transferFocus();
}
};
field.getActionMap().put("enter-action", myAction);
field.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "enter-action");
field.addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(final KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("Pressed enter inside JComboBox");
field.transferFocus();
}
}
});
field.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(final KeyEvent e)
{
System.out.println("Pressed enter inside JComboBox #2");
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
field.transferFocus();
/*This will fire but will not transfer the focus to the next control*/
System.out.println("Transfered the focus from JComboBox");
}
}
});
field.getEditor().addActionListener(new ActionListener()
{
@Override public void actionPerformed(ActionEvent arg0)
{
field.transferFocus();
}
});
System.out.println("Added enter events to JComboBox");
}