Reputation: 704
The code bellow was supposed to transfer the focus to the next control after hitting the Enter key at anytime, the event fires but .transferFocus is not transfering the focus, what could be wrong? Thank you
//JSpinner Creation Code:
private javax.swing.JSpinner edtStockMax;
edtStockMax = new javax.swing.JSpinner();
edtStockMax.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
//Code to bind the Enter key
JSpinnerField1.getActionMap().put("enter-action", new AbstractAction("enter-action")
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Transfer focus inside JSpinner");
field.transferFocus();
}
});
JSpinnerField1.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("ENTER"), "enter-action");
Upvotes: 0
Views: 865
Reputation: 1
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher( event -> {
if ( event.getID() == KeyEvent.KEY_PRESSED && event.getKeyCode() == KeyEvent.VK_ENTER ) {
Component owner = manager.getFocusOwner();
if ( owner instanceof JFormattedTextField ) {
if ( spinner.getEditor().getComponent( 0 ) == owner ) {
manager.focusNextComponent();
return true;
}
}
}
return false;
} );
Upvotes: -1
Reputation: 2371
You could make a custom NumberEditor (inner) class for handling the focus change. Here is a sample of a class:
class CustomNumberEditor extends JSpinner.NumberEditor implements KeyListener{
private JFormattedTextField textField;
public CustomNumberEditor(JSpinner spinner){
super(spinner);
textField = getTextField();
textField.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER){
textField.transferFocus();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
You have to set it as your custom editor. Here's the code:
final JSpinner edtStockMax = new JSpinner();
edtStockMax.setModel(new SpinnerNumberModel(0, 0, 100, 10));
edtStockMax.setEditor(new CustomNumberEditor(edtStockMax));
Upvotes: 0