如何将JPasswordField限制为4位数?

时间:2017-05-16 17:49:20

标签: java jpasswordfield

我刚刚在这里看到了一些问题,但没有一个能为我解决问题。我有一个JPasswordField我需要用户 输入EscPin JPasswordField

中的4位数以上
private void EscPinActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
}

private javax.swing.JButton Entrar;
private javax.swing.JTextField EscNConta;
private javax.swing.JPasswordField EscPin;
private javax.swing.JLabel Logo;
private javax.swing.JLabel NConta;
private javax.swing.JLabel Pin;
private javax.swing.JButton Sair;

1 个答案:

答案 0 :(得分:1)

您必须获取 JPasswordField 的内部文档。试试这个它会起作用。

PlainDocument d=(PlainDocument) jPasswordField1.getDocument();
d.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.
        }



    });