有没有办法在Java的keyListener方法中区分字符和整数?

huangapple go评论63阅读模式
英文:

Is there a way to differentiate between chars and integers using keyListener methods in Java?

问题

我目前正在尝试使用不同的Java事件处理程序来为我的大学做一些事情,但当我尝试编写一个将用户输入分离为字符和整数并将每种类型放入不同文本字段的程序时,我真的不知道要使用哪些方法!所以如果有人能够提供一个方法来做到这一点,我将不胜感激。无论如何,谢谢!

英文:

I'm currently trying to use different Java event handlers to do stuff for my university, but when I tried to write a programme that separates the user's input into chars and integers and put each type in a different textfield I just didn't know what methods to use!
So I would really appreciate it if anyone could give me a way to do so.
Thanks anyway!

答案1

得分: 1

textField1.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        super.keyPressed(e);
        char c = e.getKeyChar();
        if (Character.isDigit(c)) {
            label.setText("数字");
        } else if (Character.isLetter(c)) {
            label.setText("字母");
        }
    }
});
英文:

You can use Character.isDigit(TheChar) true if integer

Character.isLetter(TheChar) true if letter

Edit : full working code to show if the pressed key is number or letter

    textField1.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            super.keyPressed(e);
            char c = e.getKeyChar();
            if (Character.isDigit(c)) {
                label.setText("number");
            } else if (Character.isLetter(c)) {
                label.setText("letter");
            }

        }
    });

huangapple
  • 本文由 发表于 2020年7月26日 00:53:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63090997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定