gpt4 book ai didi

java - 理解 Java 中的 KeyEvent 的问题

转载 作者:行者123 更新时间:2023-11-30 06:43:08 27 4
gpt4 key购买 nike

我目前正在尝试制作一个程序,其中输入三个按钮,每次都会发生不同的情况。

我知道我必须使用keyPressed,但这确实让我感到困惑,因为当我运行程序时,它不会等待我输入任何内容。

由于我对一般编程还很陌生,所以我一直在遵循在线指南,因此如果您有更好的方法来完成所有这些工作,请务必说出来。

import java.awt.event.KeyEvent;

public class Trial {

public static void main(String[] args) {
System.out.println("Welcome to the Medical Registration Form program.");
System.out.println("To enter a new patient's details, press 'N'");
System.out.println("To access an existing pateient's details, press 'S'");
System.out.println("To see all patient deatils currently saved, press 'P'");
}

public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_S) {
System.out.println("You pressed a valid button");
} else {
System.out.println("You pressed a bad button!");
e.consume();
}
}
}

最佳答案

如果您想使用控制台,请按照以下代码片段操作:

public class Demo{

public static void main(String[] args) {
// TODO code application logic here

System.out.println("Welcome to the Medical Registration Form program.");
System.out.println("To enter a new patient's details, press 'N'");
System.out.println("To access an existing pateient's details, press 'S'");
System.out.println("To see all patient deatils currently saved, press 'P'");
Scanner scan = new Scanner(System.in);
String input = scan.next();

if(input.matches("S")){
System.out.println("You pressed a valid button");
} else {
System.out.println("You pressed a bad button!");

}
}

否则,从 Jframe 扩展并实现 KeyListener,如下所示:

public class Demo extends JFrame implements KeyListener{

public Demo(){

this.addKeyListener(this);
}

public static void main(String[] args) {
// TODO code application logic here

System.out.println("Welcome to the Medical Registration Form program.");
System.out.println("To enter a new patient's details, press 'N'");
System.out.println("To access an existing pateient's details, press 'S'");
System.out.println("To see all patient deatils currently saved, press 'P'");
Demo demo = new Demo();
}

@Override
public void keyPressed(KeyEvent e) {

int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_S){
System.out.println("You pressed a valid button");
} else {
System.out.println("You pressed a bad button!");
e.consume();
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

关于java - 理解 Java 中的 KeyEvent 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44073176/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com