Java – how do I limit the length of input I want in jtextfield?

username = new JTextField("");
username = new JTextField("");
    username.setBounds(330,550,230,30);
    username.addActionListener(this);
    username.requestFocus(); // sets focus on JTextField
    this.add(username);

Solution

JTextField username = new JTextField("") ;
JTextField username = new JTextField("") ;
final int limit = 10;
username .setDocument(new PlainDocument(){
    @Override
    public void insertString(int offs,String str,AttributeSet a)
            throws BadLocationException {
        if(getLength() + str.length() <= limit)
            super.insertString(offs,str,a);
    }
});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>