【问题标题】:need to separate a keylistener from a class into another需要将 keylistener 从一个类中分离到另一个类中
【发布时间】:2015-08-22 19:34:00
【问题描述】:

所以我在 java 上编程,在尝试将 keylistener 实现到不同的类时遇到了麻烦,所以我有一个名为 GUI 的类和一个名为 convertir 的 txtbox。当它在 GUI 上执行时,它不允许用户输入任何字母,只允许用户输入数字。

txtConvertir = new JTextField();
            txtConvertir.addKeyListener(new KeyAdapter() {


                public void keyTyped(java.awt.event.KeyEvent evento) {

                    // método que impide que las letras sean ingresadas en el text
                    // box
                    char c = evento.getKeyChar();

                    if (c < '0' || c > '9')
                        evento.consume();

                    }

            });


            txtConvertir.setBounds(158, 44, 224, 20);
            panel.add(txtConvertir);
            txtConvertir.setColumns(10);

然后我在另一个名为 main 的包中添加了另一个类,以及一个名为 validarprecio 的方法。

void validarprecio(){

}

有人可以帮我将方法从 GUI 移动到 validarprecio 方法,所以它仍然可以在 gui 上运行吗?请我在网上搜索过,但我不明白。提前致谢

【问题讨论】:

    标签: java eclipse class keylistener


    【解决方案1】:

    接口编程

    您不能(通常)将您的方法命名为 validarprecio,而应将其命名为 keyTypedextend 来自 KeyAdapter,就像在您的内部类示例中一样。例如,

    class ValidarPrecio extends KeyAdapter {
        public void keyTyped(java.awt.event.KeyEvent evento) {
            char c = evento.getKeyChar();
            if (c < '0' || c > '9') {
                evento.consume();
            }
        }
    }
    

    然后你可以写类似的东西

    txtConvertir = new JTextField();
    ValidarPrecio validarprecio = new ValidarPrecio();
    txtConvertir.addKeyListener(validarprecio);
    

    【讨论】:

    • 天哪,非常感谢你救了我的命!它工作得很好而且很顺利!谢谢!!!
    • @DanielEstebanLadinoTorres 很高兴为您提供帮助。欢迎来到 StackOverflow,请拨打tour。如果这回答了您的问题,请accept
    • @Elliott Frisch 好的,我会的!
    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2019-03-23
    • 1970-01-01
    • 2021-12-25
    • 2019-01-22
    • 2017-04-25
    • 2011-08-26
    • 2021-06-25
    相关资源
    最近更新 更多