Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在我的Java程序中添加一个简单的回车键功能_Java_Eclipse_Swing_Keyboard_Enter - Fatal编程技术网

在我的Java程序中添加一个简单的回车键功能

在我的Java程序中添加一个简单的回车键功能,java,eclipse,swing,keyboard,enter,Java,Eclipse,Swing,Keyboard,Enter,我有一个小Java程序完全可以工作。当我输入pin码时,我想让“回车”键起作用。在我写这篇文章时,我只能点击按钮使其工作,所以我想添加这个简单的功能,而不改变所有的代码 这就是我写这篇文章的原因,因为我已经找到了几个链接,但是没有一个与我的情况相符,因为我知道我已经有一个代码在工作。我需要调整我在那里发现的内容: 事实上,他们都在展示nohting的解决方案,这对我没有帮助,因为我无法在自己的程序中使用他们所做的 如您所见,这是“确定”按钮,我需要单击或按“回车”键 这是我的代码,您建议如

我有一个小Java程序完全可以工作。当我输入pin码时,我想让“回车”键起作用。在我写这篇文章时,我只能点击按钮使其工作,所以我想添加这个简单的功能,而不改变所有的代码

这就是我写这篇文章的原因,因为我已经找到了几个链接,但是没有一个与我的情况相符,因为我知道我已经有一个代码在工作。我需要调整我在那里发现的内容:

事实上,他们都在展示nohting的解决方案,这对我没有帮助,因为我无法在自己的程序中使用他们所做的

如您所见,这是“确定”按钮,我需要单击或按“回车”键

这是我的代码,您建议如何使用Enter键

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {

    private static final long serialVersionUID = 1L;

    private JPanel container = new JPanel();
    private JPasswordField p1 = new JPasswordField(4);
    private JLabel label = new JLabel("Enter Pin: ");
    private JButton b = new JButton("OK");


    public Main() {
        this.setTitle("NEEDS");
        this.setSize(300, 500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        container.setBackground(Color.white);
        container.setLayout(new BorderLayout());
        container.add(p1);
        JPanel top = new JPanel();

        PlainDocument document =(PlainDocument)p1.getDocument();

        b.addActionListener(new BoutonListener());

        top.add(label);
        top.add(p1);
        p1.setEchoChar('*');
        top.add(b);


        document.setDocumentFilter(new DocumentFilter(){

            @Override
            public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                String string =fb.getDocument().getText(0, fb.getDocument().getLength())+text;

                if(string.length() <= 4)
                super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates.
            }
        });

        this.setContentPane(top);
        this.setVisible(true);
    }

    class BoutonListener implements ActionListener {
        private final AtomicInteger nbTry = new AtomicInteger(0);
        ArrayList<Integer> pins = readPinsData(new File("bdd.txt"));

        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent e) {
            if (nbTry.get() > 2) {
                JOptionPane.showMessageDialog(null,
                        "Pin blocked due to 3 wrong tries");
                return;
            }
            final String passEntered=p1.getText().replaceAll("\u00A0", "");
            if (passEntered.length() != 4) {
                JOptionPane.showMessageDialog(null, "Pin must be 4 digits");
                return;
            }
            //JOptionPane.showMessageDialog(null, "Checking...");
            //System.out.println("Checking...");
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    boolean authenticated = false;
                    ImageIcon imgAngry = new ImageIcon("angry.png");
                    ImageIcon imgHappy = new ImageIcon("happy.png");

                    if (pins.contains(Integer.parseInt(passEntered))) {
                        JOptionPane.showMessageDialog(null, "Pin correct", "Good Pin", JOptionPane.INFORMATION_MESSAGE, imgHappy);
                        authenticated = true;
                    }

                    if (!authenticated) {
                        JOptionPane.showMessageDialog(null, "Wrong Pin", "Wrong Pin", JOptionPane.INFORMATION_MESSAGE, imgAngry);
                        nbTry.incrementAndGet();
                    }
                    return null;
                }
            };
            worker.execute();
        }

    }

    // Reading bdd.txt file
    static public ArrayList<Integer> readPinsData(File dataFile) {
        final ArrayList<Integer> data=new ArrayList<Integer>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(dataFile));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    try {
                        data.add(Integer.parseInt(line));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        System.err.printf("error parsing line '%s'\n", line);
                    }
                }
            } finally {
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error:"+e.getMessage());
        }

        return data;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main();
            }
        });

    }
}
import java.io.*;
导入java.util.*;
导入java.util.concurrent.AtomicInteger;
导入javax.swing.*;
导入javax.swing.text.AttributeSet;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.DocumentFilter;
导入javax.swing.text.PlainDocument;
导入java.awt.*;
导入java.awt.event.*;
公共类主框架{
私有静态最终长serialVersionUID=1L;
私有JPanel容器=新JPanel();
私有JPasswordField p1=新的JPasswordField(4);
专用JLabel标签=新JLabel(“输入Pin:”);
私有JButton b=新JButton(“OK”);
公用干管(){
本条。设定标题(“需要”);
这个。设置大小(300500);
此.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
此.setLocationRelativeTo(空);
容器.立根台(颜色.白色);
container.setLayout(新的BorderLayout());
容器。添加(p1);
JPanel top=新的JPanel();
PlainDocument文档=(PlainDocument)p1.getDocument();
b、 addActionListener(新的BoutonListener());
添加(标签);
添加(p1);
p1.setEchoChar('*');
顶部。添加(b);
document.setDocumentFilter(新的DocumentFilter(){
@凌驾
public void replace(DocumentFilter.FilterBypass fb、整数偏移量、整数长度、字符串文本、属性集属性)引发BadLocationException{
String String=fb.getDocument().getText(0,fb.getDocument().getLength())+文本;
if(string.length()2){
JOptionPane.showMessageDialog(null,
“3次错误尝试导致Pin被阻塞”);
回来
}
最后一个字符串passEntered=p1.getText().replaceAll(“\u00A0”,”);
如果(passEntered.length()!=4){
showMessageDialog(null,“Pin必须是4位数字”);
回来
}
//showMessageDialog(null,“正在检查…”);
//System.out.println(“检查…”);
SwingWorker worker=新SwingWorker(){
@凌驾
受保护的Void doInBackground()引发异常{
布尔值=假;
ImageIcon imgAngry=新的ImageIcon(“angry.png”);
ImageIcon imgHappy=新的ImageIcon(“happy.png”);
if(pins.contains(Integer.parseInt(passEntered))){
JOptionPane.showMessageDialog(null,“Pin正确”,“Pin正确”,JOptionPane.INFORMATION_MESSAGE,imgHappy);
已验证=真;
}
如果(!已验证){
JOptionPane.showMessageDialog(null,“错误的Pin”,“错误的Pin”,JOptionPane.INFORMATION\u MESSAGE,imgAngry);
nbTry.incrementAndGet();
}
返回null;
}
};
worker.execute();
}
}
//读取bdd.txt文件
静态公共ArrayList readPinsData(文件数据文件){
最终ArrayList数据=新ArrayList();
试一试{
BufferedReader reader=新BufferedReader(新文件读取器(数据文件));
弦线;
试一试{
而((line=reader.readLine())!=null){
试一试{
data.add(Integer.parseInt(line));
}捕获(数字格式){
e、 printStackTrace();
System.err.printf(“错误分析行'%s'\n',行);
}
}
}最后{
reader.close();
}
}捕获(例外e){
e、 printStackTrace();
System.err.println(“错误:+e.getMessage());
}
返回数据;
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
新的Main();
}
});
}
}

我认为这段代码应该指导你,在你的课堂上添加以下代码:

    @Override
public void actionPerformed(ActionEvent e) {
    b.doClick();
}

我认为这个片段应该指导你,在你的课堂上添加以下代码:

    @Override
public void actionPerformed(ActionEvent e) {
    b.doClick();
}
JTextField
(它继承自
JPasswordField
)仅为该功能提供
ActionListener
支持

p1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        b.doClick(); // Re-use the Ok buttons ActionListener...
    }
});
查看更多详细信息

JTextField
(它继承自)仅为该功能提供了
ActionListener
支持

p1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        b.doClick(); // Re-use the Ok buttons ActionListener...
    }
});

查看了解更多详细信息编辑:哦,抱歉。未识别您正在使用Swing/AWT。这是SWT功能,因此对您的问题没有帮助

我使用TraverseListener实现了该行为。您可以尝试以下方法:

        p1.addTraverseListener(new TraverseListener() {
        @Override
        public void keyTraversed(TraverseEvent e) {
            switch (e.detail) {
              case SWT.TRAVERSE_RETURN:
                doWhateverYourButtonClickDoesHere();
                break;
            }
        }
    });

编辑:哦,对不起。我不知道您正在使用Swing/AWT。这是SWT功能,因此对您的问题没有帮助

我使用TraverseListener实现了该行为。您可以尝试以下方法:

        p1.addTraverseListener(new TraverseListener() {
        @Override
        public void keyTraversed(TraverseEvent e) {
            switch (e.detail) {
              case SWT.TRAVERSE_RETURN:
                doWhateverYourButtonClickDoesHere();
                break;
            }
        }
    });
充实:

[调用
按钮.doClick()