How to limit the number of digits in a JPasswordField in Java?

后端 未结 4 767
轻奢々
轻奢々 2020-12-12 01:20

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

First, how to limit the number of digits that can be entered by the user ? Actually I

相关标签:
4条回答
  • 2020-12-12 01:48

    JPasswordField limit characters to 4

    private void edtPinCodeKeyReleased(java.awt.event.KeyEvent evt) {                                       
        if (String.valueOf(edtPinCode.getPassword()).trim().length() > 4) 
            edtPinCode.setText(String.valueOf(edtPinCode.getPassword()).trim().substring(0, 4));
    } 
    
    0 讨论(0)
  • 2020-12-12 01:49

    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.

    Don't use setPrefferedSize() instead use this constructor JPasswordField(int col) .Read more about that here Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

    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 ?

    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);
        }
    
    }
    

    enter image description here

    0 讨论(0)
  • 2020-12-12 01:51

    First, how to limit the number of digits that can be entered by the user ?

    • See this Q&A: How To limit the number of characters in JTextField? As JPasswordField extends from JTextField it should perfectly work.
    • As @nachokk correctly pointed out, working with document filters (like he does in his answer) is a more flexible option. You can read more about it in Concepts: About Documents and Implementing a Document Filter sections of Text Component Features official article.

    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.

    • Don't set fixed sizes when you're working with Swing. See this topic: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?.
    • You can use setColumns(int columns) instead to indicate the preferred size of the text field.
    • See How to Use Password Fields tutorial.
    0 讨论(0)
  • 2020-12-12 02:05

    Generalize code and Easy Way to solve this question

    Four Digit limit the number in a JPasswordField (Java) using netbeans..

    //JPasswordField Variable name is "Password_Field_Demo"
    //Jlabel variable name is "lbl_register"
    
    public class Register extends javax.swing.JFrame {
        static int count=1;     //static variable(count) initialize on first time..
    
    //Default Constructor
    public Register() {
        initComponents();
    }
    
    //KeyTyped(KeyEvent evt) Method in Password_Field_Demo
    private void Password_Field_DemoKeyTyped(java.awt.event.KeyEvent evt) {                                    
        char c = evt.getKeyChar(); //get the Character
        if(Character.isDigit(c))  //isDigit() method on Character and Enter only Digit or number
        {
            if(count>4)
            {                    
                evt.consume();//Greater than Four Digit to consume()method ..Not Input more than Four Digit
                lbl_register.setText(" Maximum Four Digit Allowed..");
            }
            else{
                count++;
                lbl_register.setText("");
            }
        }
        if((c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE))
        {
            if(count>1)
                count--;
            lbl_register.setText("");
        }
    
       //lbl_register.setText(" count :"+count);
    
    
    }  //End Password_Field_DemoKeyTyped()
    
    0 讨论(0)
提交回复
热议问题