Detect enter press in JTextField

前端 未结 10 1688
说谎
说谎 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
        }
    }
    

提交回复
热议问题