java - 在我的 Java 程序中添加一个简单的 Enter 键功能

标签 java eclipse swing keyboard enter

我有一个可以正常运行的小 Java 程序。当我输入密码时,我想让“Enter”键起作用。在我写这篇文章时,我只能点击按钮使其工作,所以我想添加这个简单的功能而不更改所有代码。

这就是我发帖的原因,因为我找到了几个链接,但没有一个符合我的情况,因为我知道我已经有一个代码可以工作。我需要调整在那里找到的内容:

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick http://tips4java.wordpress.com/2008/10/10/key-bindings/ http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html http://www.javaprogrammingforums.com/java-swing-tutorials/3171-jbutton-enter-key-keyboard-action.html http://www.rgagnon.com/javadetails/java-0253.html

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

Enter key

如您所见,这是我需要单击或按下“Enter”的“确定”按钮

这是我的代码,您有什么建议可以让 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();
            }
        });

    }
}

最佳答案

JTextField(JPasswordField 继承自)为该功能提供 ActionListener 支持。

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

看看How to use text fields了解更多详情

关于java - 在我的 Java 程序中添加一个简单的 Enter 键功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22657100/

相关文章:

java - 使用 Jackson 解析 JSON Bing 结果

java - Spring Security 预身份验证

eclipse - 使用在 MPS 工具/intellij idea 之外的 jetBrains MPS 工具中创建的语言

Java Netbeans 8.0 Jframe GUI 程序 - arraylist 中的每个索引值未显示在 jtextArea 中的单独行上

java - Swing MenuEvent menuCanceled

Java Swing - 更好的字体平滑

java - Play 框架应用程序中的内存泄漏

java - 获取 javadoc 时出现异常 : Unknown javadoc format

java - 为什么更改 WEB-INF/web.xml 不会导致 tomcat 重新加载上下文?

c - 即使不包含在 C 中,函数也是可见的