0

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");
paul-2011
  • 675
  • 10
  • 27
  • If the spinner isn't in editor mode then the editor isn't visible so it won't receive events. I would guess you also need to do a Key Binding on the JSpinner object as well. – camickr Mar 07 '13 at 17:09
  • have you tried `requestFocusInWindow()` (See [this](http://stackoverflow.com/questions/15223416/focus-on-component-when-a-panel-is-loaded/15223913#15223913) example) vs `transferFocus()`? – David Kroukamp Mar 07 '13 at 17:26
  • It is in Editor Mode, the code above works except for the procedure "transferFocus()", it runs without errors but doesn't transfer the focus to the next control, the focus stays on the JSpinner. – paul-2011 Mar 07 '13 at 18:22
  • I don't know how I can use requestFocusInWindow(), I would need to get the next control after the JSpinner to do that? If transferFocus() worked it would be much easier. – paul-2011 Mar 07 '13 at 18:45

1 Answers1

0

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));
Slimu
  • 2,301
  • 1
  • 22
  • 28