How to get a JTextField to respond to the enter key

℡╲_俬逩灬. 提交于 2019-12-18 09:05:07

问题


So I want to get a JTexField to put the text in it into a JTextArea when the enter key is pressed with the cursor in it. Can anyone help?


回答1:


Forget about using KeyListener for Swing components.

This listener was designed for use with AWT components does not provide a reliable interaction mechanism for JTextComponents.

Use an ActionListener instead - on the vast majority of systems an ActionEvent is dispatched by the JTextField when enter is pressed.

myTextField.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
       myTextArea.append(myTextField.getText() + "\n");
    }
});



回答2:


    JTextArea myJTextArea = new JTextArea();
    myJTextArea.setBounds(200, 15, 258, 28);
    myJPanel.add(myJTextArea);

    JTextField myJTextField = new JTextField();
    myJTextField.setBounds(15, 15, 130, 28);
    myJPanel.add(myJTextField);
    myJTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                myJTextArea.setText(myJTextField.getText());
            }
        }
    });


来源:https://stackoverflow.com/questions/16378888/how-to-get-a-jtextfield-to-respond-to-the-enter-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!