英文:
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");
}
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论