代码轰鸣声应该在任何时候点击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");
答案 0 :(得分: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));