如何在Jtextfield中限制我想要的输入长度?

时间:2011-05-26 23:34:34

标签: java jtextfield jformattedtextfield

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

1 个答案:

答案 0 :(得分:7)

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