how do i limit the length of the input i want inside a Jtextfield?

▼魔方 西西 提交于 2019-12-10 18:45:54

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/6146274/how-do-i-limit-the-length-of-the-input-i-want-inside-a-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!