Detect enter press in JTextField

前端 未结 10 1621
说谎
说谎 2020-11-29 03:06

Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.

相关标签:
10条回答
  • 2020-11-29 03:43

    First add action command on JButton or JTextField by:

    JButton.setActionCommand("name of command");
    JTextField.setActionCommand("name of command");
    

    Then add ActionListener to both JTextField and JButton.

    JButton.addActionListener(listener);
    JTextField.addActionListener(listener);
    

    After that, On you ActionListener implementation write

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand();
    
        if(actionCommand.equals("Your actionCommand for JButton") || actionCommand.equals("Your   actionCommand for press Enter"))
        {
            //Do something
        }
    }
    
    0 讨论(0)
  • 2020-11-29 03:45

    Just use this code:

    SwingUtilities.getRootPane(myButton).setDefaultButton(myButton);
    
    0 讨论(0)
  • 2020-11-29 03:52

    Add an event for KeyPressed.

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
      if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
          // Enter was pressed. Your code goes here.
       }
    } 
    
    0 讨论(0)
  • 2020-11-29 03:53
    public void keyReleased(KeyEvent e)
    {
        int key=e.getKeyCode();
        if(e.getSource()==textField)
        {
            if(key==KeyEvent.VK_ENTER)
            { 
                Toolkit.getDefaultToolkit().beep();
                textField_1.requestFocusInWindow();                     
            }
        }
    

    To write logic for 'Enter press' in JTextField, it is better to keep logic inside the keyReleased() block instead of keyTyped() & keyPressed().

    0 讨论(0)
提交回复
热议问题