我正在构建一个自动柜员机模拟器,我希望在按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中检测到按键事件?如有任何帮助,我们将不胜感激!

推荐答案

我希望在按Enter键时验证PIN码

简单的答案是使用一个ActionListener,当用户"操作"文本字段时调用它(即,在大多数情况下,在该字段被聚焦时按Enter键)

A Minimal, Reproducible Example...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class TestPane extends JPanel {

        private JTextField pinField;

        public TestPane() {
            setBorder(new EmptyBorder(32, 32, 32, 32));
            setLayout(new GridBagLayout());

            pinField = new JTextField(4);
            add(pinField);

            pinField.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String pinText = pinField.getText();
                    try {
                        int pinValue = Integer.parseInt(pinText);
                        if (pinValue != 1234) {
                            JOptionPane.showMessageDialog(TestPane.this, "Invalid PIN", "Error", JOptionPane.ERROR_MESSAGE);
                        } else {
                            // Now I'd use an observer here to notify interested
                            // parties that the pin was validated
                        }
                    } catch (NumberFormatException exp) {
                        JOptionPane.showMessageDialog(TestPane.this, "Invalid PIN", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
        }

    }
}

请参见:

了解更多详细信息.

我也建议看看Implementing a Document Filter,如果你有兴趣限制什么用户可以输入到文本字段(即实时验证). 这也将允许您"自动"验证PIN,一旦它达到所需的位数.

你也应该花时间学习和使用可用的layout managers,这只会为你节省很多时间和头痛.

Java相关问答推荐

javafx getHostServices(). showDocument()调出Chrome而不是默认浏览器(Linux)

填写文本字段后锁定PDF

为什么一个java函数会返回一个作为参数传递给它的对象?

neo4j java驱动程序是否会在错误发生时自动回滚事务?

使用java访问具体子类特定方法的最佳方法是什么?

使用意向过滤器从另一个应用程序启动服务

RESTful框架类字段是安全的还是不安全的

什么是Java原子属性的正确getter和setter

测试期间未执行开放重写方法

为什么同步数据块无效?

在macOS上读取文件会导致FileNotFound,即使文件存在(并且具有权限)

Dijkstra搜索算法的实现

一对多关系和ID生成

try 使用预准备语句占位符获取信息时出现Try-With-Resources错误

插入中的JOOQ序列,设置为VS值

在具有Quarkus Panache的PostgreSQL中将JSON数据存储为JSONB时,会将其存储为转义字符串

如何利用OpenTelemeter将初始值(零)输出到普罗米修斯

如何正确使用java.time类?

使用StringBuilder和append方法创建字符串时Java字符串内部方法的问题

在对象列表上调用提取后,如何判断没有值为空?