在此代码段中我如何使用KeyListener错误?

时间:2018-10-26 05:17:30

标签: jpanel jtextfield keylistener keyevent

我试图按Enter键转到下一个文本字段(TextField2),而不是(默认情况下)按JOptionPane的OK_CANCEL_OPTION中的ok键。

   JTextField textField1 = new JTextField("");
   JTextField textField2 = new JTextField("");

   JPanel panel = new JPanel(new GridLayout(0,1));

   panel.add(new JLabel ("Check"));
   panel.add(textField1);
   panel.add(new JLabel ("Cash" ));
   panel.add(textField2);
   textField1.addAncestorListener(new SetFocus());
   textField1.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
           textField2.addAncestorListener(new SetFocus());
        }
    }

});

   JOptionPane.showConfirmDialog(null, panel, "Deposit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); 

1 个答案:

答案 0 :(得分:0)

使用textfield2.requestFocus()代替添加祖先侦听器。