KeyListener的正确用法是什么? [英] What is the proper use of KeyListener?

查看:180
本文介绍了KeyListener的正确用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在尝试提取jTextFields中的数据,并且此错误消息不断弹出,指向以下内容:

So I have been working on trying to extract the data in my jTextFields and this error message keeps popping up referring to an:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: calcu.turkey (<--my class) cannot be cast to java.awt.event.KeyListener

      jTextField2.addKeyListener(new java.awt.event.KeyListener() {

        @Override
        public void keyTyped(KeyEvent ke) {
            //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent ke) {
          //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //To change body of generated methods, choose Tools | Templates.
        }
    });
    jTextField2.addKeyListener((KeyListener) this);
    jTextField2.setFont(new java.awt.Font("Times New Roman", 0, 10)); // NOI18N
    jTextField2.setText("0");
    getContentPane().add(jTextField2);
    jTextField2.setBounds(250, 40, 70, 20);

最重要的是以下行:jTextField2.addKeyListener((KeyListener) this);,因为它将(KeyListener)视为错误.我想知道如何正确添加KeyListener,以便它在文本字段中获取数字.

Most importantly this line: jTextField2.addKeyListener((KeyListener) this); as it views the (KeyListener) as an error. I was wondering how do you properly add the KeyListener so it grab the number in the textfield.

推荐答案

您不使用KeyListener.您很少需要这样做.有更好的API可供使用.

You don't use a KeyListener. Rarely do you have a need to do this. There are better API's to be used.

例如,当使用文本组件时,您可能会使用DocumentListener(请参见实施文档过滤器).

For example when using a text component you would probably use a DocumentListener (see How to Write a Document Listener) or DocumentFilter (see Implementing a Document Filter).

我想知道如何正确添加KeyListener,以便它在文本字段中获取数字.

I was wondering how do you properly add the KeyListener so it grab the number in the textfield.

通常,您会在一些不相关的事件中获取该号码.例如,您在表单上有一个提交"按钮.然后,在这种情况下,您将向按钮添加一个ActionListener,然后在想要提交表单时使用文本字段的getText()方法.

Normally you would grab the number on some unrelated event. For example you have a "Submit" button on a form. Then in that case you would add an ActionListener to the button and then use the getText() method of the text field when you want to submit the form.

此外,我上面引用的Swing教程中的How to Write a Key Listener部分.

Also, the Swing tutorial that I referenced above has a section on How to Write a Key Listener.

这篇关于KeyListener的正确用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆