如何限制 Java 中 JPasswordField 中的位数?

2022-01-22 00:00:00 limit passwords security java swing

我的 Java 代码在 Eclipse 中运行,但我需要添加一些功能.

I have my Java code working in Eclipse but I need to add a few functionnality.

首先,如何限制用户可以输入的位数?实际上我有一个 JPasswordField 可以让一个人输入密码,我希望这个 JPasswordField 最多限制为 4 位数字.那么如何在输入 4 位后立即停止输入呢?

First, how to limit the number of digits that can be entered by the user ? Actually I have a JPasswordField that let a person enter a pin Code, and I would like this JPasswordField limited to 4 digits maximum. So how to stop the input as soon as 4 digits are entered ?

那么,我该如何使用 JPassword 框的大小呢?有没有办法像 JTextField 一样修改它?因为我的行p1.setPreferredSize(new Dimension(100, 25));"似乎并没有真正让我修改框的大小.

Then, how can I play with the size of the JPassword box ? Is there a way to modify it just like a JTextField for example ? Because my line "p1.setPreferredSize(new Dimension(100, 25));" does not seem to really let me modify the size of the box.

如您所见,JPassworldField 框有一个默认大小,我不知道如何轻松修改.

As you can see, the JPassworldField box has a default size that I can not figure out how to modify easily.

这是我的代码:

package codePin;

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.*;
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());
        JPanel top = new JPanel();
        p1.setPreferredSize(new Dimension(100, 25)); //How to really modifiy this ?

        b.addActionListener(new BoutonListener());

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


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

    class BoutonListener implements ActionListener {
        private final AtomicInteger nbTry = new AtomicInteger(0);

        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent e) {
            if (nbTry.get() > 2) {
                JOptionPane.showMessageDialog(null,
                        "Pin blocked due to 3 wrong tries");
                return;
            }
            if (p1.getText().replaceAll("u00A0", "").length() != 4) {
                // System.out.println("Pin must be 4 digits");
                JOptionPane.showMessageDialog(null, "Ping must be 4 digits");
                return;
            }
            System.out.println("Checking...");
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    boolean authenticated = false;
                    ArrayList<Integer> pins = new ArrayList<Integer>();
                    readPinsData(new File("bdd.txt"), pins);
                    String[] thePins = new String[pins.size()];
                    for (int i = 0; i < thePins.length; i++) {
                        thePins[i] = pins.get(i).toString();
                    }
                    String passEntered = String.valueOf(p1);
                    for (String thePin : thePins) {
                        if (passEntered.equals(thePin)
                                && p1.getText().length() == 4) {
                            System.out.println(":)");
                            authenticated = true;
                            break;
                        }
                    }
                    if (!authenticated) {
                        System.out.println(":(");
                        nbTry.incrementAndGet();
                    }
                    return null;
                }
            };
            worker.execute();
        }

    }

    // Accessing pins Bdd file
    static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
        boolean err = false;
        try {
            Scanner scanner = new Scanner(dataFile);
            String line;
            while (scanner.hasNext()) {
                line = scanner.nextLine();
                try {
                    data.add(Integer.parseInt(line));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    err = true;
                }
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            err = true;
        }

        return err;
    }

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

    }
}

有什么想法吗?谢谢.

弗洛伦特

这是我用 nachokk 的解决方案编辑的代码:

Here is my code edited with nachokk's solution :

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());
        JPanel top = new JPanel();

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

        b.addActionListener(new BoutonListener());

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


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


        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.
            }



        });
        container.add(p1);
    }

    class BoutonListener implements ActionListener {
        private final AtomicInteger nbTry = new AtomicInteger(0);

        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent e) {
            if (nbTry.get() > 2) {
                JOptionPane.showMessageDialog(null,
                        "Pin blocked due to 3 wrong tries");
                return;
            }
            if (p1.getText().replaceAll("u00A0", "").length() != 4) {
                // System.out.println("Pin must be 4 digits");
                JOptionPane.showMessageDialog(null, "Ping must be 4 digits");
                return;
            }
            System.out.println("Checking...");
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    boolean authenticated = false;
                    ArrayList<Integer> pins = new ArrayList<Integer>();
                    readPinsData(new File("bdd.txt"), pins);
                    String[] thePins = new String[pins.size()];
                    for (int i = 0; i < thePins.length; i++) {
                        thePins[i] = pins.get(i).toString();
                    }
                    String passEntered = String.valueOf(p1);
                    for (String thePin : thePins) {
                        if (passEntered.equals(thePin)
                                && p1.getText().length() == 4) {
                            System.out.println(":)");
                            authenticated = true;
                            break;
                        }
                    }
                    if (!authenticated) {
                        System.out.println(":(");
                        nbTry.incrementAndGet();
                    }
                    return null;
                }
            };
            worker.execute();
        }

    }

    // Fonction permettant d'accéder/lire notre BDD de pins (fichier .txt)
    static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
        boolean err = false;
        try {
            Scanner scanner = new Scanner(dataFile);
            String line;
            while (scanner.hasNext()) {
                line = scanner.nextLine();
                try {
                    data.add(Integer.parseInt(line));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    err = true;
                }
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            err = true;
        }

        return err;
    }

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

    }
}

推荐答案

如何使用 JPassword 框的大小?有没有办法例如像 JTextField 一样修改它?因为我的线p1.setPreferredSize(新维度(100, 25));"似乎不是真的让我修改框的大小.

How can I play with the size of the JPassword box ? Is there a way to modify it just like a JTextField for example ? Because my line "p1.setPreferredSize(new Dimension(100, 25));" does not seem to really let me modify the size of the box.

不要使用 setPrefferedSize() 而是使用此构造函数 JPasswordField(int col).阅读更多关于这里 我应该避免在 Java Swing 中使用 set(Preferred|Maximum|Minimum)Size 方法?

如何限制可以输入的位数用户?实际上我有一个 JPasswordField 可以让一个人输入密码代码,我希望这个 JPasswordField 限制为 4 位最大限度.那么如何在输入 4 位后立即停止输入呢?

How to limit the number of digits that can be entered by the user ? Actually I have a JPasswordField that let a person enter a pin Code, and I would like this JPasswordField limited to 4 digits maximum. So how to stop the input as soon as 4 digits are entered ?

对于限制输入,您可以使用 DocumentFilter,如下例所示.

For limit input you can use DocumentFilter as shown in example below.

 public class JPasswordFieldTest {

    private JPanel panel;

    public JPasswordFieldTest() {
        panel = new JPanel();
        //set horizontal gap
        ((FlowLayout) panel.getLayout()).setHgap(2);

        panel.add(new JLabel("Enter pin :"));
        JPasswordField passwordField = new JPasswordField(4);
        PlainDocument document = (PlainDocument) passwordField.getDocument();
        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.
                }
            }

        });
        panel.add(passwordField);
        JButton button = new JButton("OK");
        panel.add(button);

    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("Password Example");
            }
        });

    }

    private static void createAndShowGUI(String str) {
        JFrame frame = new JFrame(str);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPasswordFieldTest test = new JPasswordFieldTest();
        frame.add(test.panel);
        frame.pack();
        frame.setVisible(true);
    }

}

相关文章