我正在构建一个自动柜员机模拟器,我希望在按Enter键时验证PIN码.然而,在初始化身份验证类之后,我遇到了ATM_Interface类中未检测到键事件的问题.以下是我的代码的相关部分:
public class Main{
public static void main(String[] args){
JFrame frame = new JFrame();
ATM_Interface atm=new ATM_Interface();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setLayout(null);
frame.add(atm);
frame.pack();
}
}
public class ATM_Interface extends JPanel {
static String Status="";
public ATM_Interface(){
this.setPreferredSize(new Dimension(200,200));
this.setBackground(Color.blue);
this.setBounds(115,67,340,340);
this.addKeyListener(new keyAdapter());
this.setFocusable(true);
Authentication auth = new Authentication();
this.requestFocusInWindow();
}
class keyAdapter extends KeyAdapter{
@Override
public void keyPressed(KeyEvent e){
switch(Status){
case "authentication":
break;
default:
add(auth);
Status="authentication";
}
System.out.println("test");
}
}
}
public class Authentication extends JPanel {
JTextField input = new JTextField();
public Authentication(){
input.setPreferredSize(new Dimension(100,50));
this.add(input);
}
public boolean getAcces(){
if(input.getText().equals("0234")){
return true;
}
else return false;
}
}
在这段代码中,ATM_InterfaceJPanel应该使用KeyAdapter捕获关键事件.但是,在初始化身份验证类并将其作为子组件添加到ATM_接口后,在ATM_接口JPanel中未检测到关键事件.
我已经try 使用questFocusInWindow()和setFocuable()将焦点设置到ATM_Interface面板,但似乎没有解决问题. 如何确保在ATM_接口JPanel中检测到按键事件?如有任何帮助,我们将不胜感激!