0

下面的代码应该在任何时候按 Enter 键后将焦点转移到下一个控件,事件触发但 .transferFocus 没有转移焦点,可能有什么问题?谢谢

//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");
4

1 回答 1

0

您可以制作一个自定义 NumberEditor(内部)类来处理焦点更改。这是一个类的示例:

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) {
        }
    }

您必须将其设置为您的自定义编辑器。这是代码:

final JSpinner edtStockMax = new JSpinner();
edtStockMax.setModel(new SpinnerNumberModel(0, 0, 100, 10));
edtStockMax.setEditor(new CustomNumberEditor(edtStockMax));
于 2013-11-22T10:48:44.227 回答