我目前正在尝试制作一个程序,其中输入了三个按钮,每次都会发生不同的事情。
我知道我必须使用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();
}
}
}
答案 0 :(得分:1)
如果您想使用控制台,请按照以下代码段进行操作:
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
}