简体   繁体   English

限制JTextField中的字符数

[英]Limit number of characters in JTextField

I try to limit the number of allowable characters to 5 by using 我尝试使用允许字符数限制为5

    try {
        jFormattedTextField2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("*****")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }

However, when I only enter 1 character, there will always be 4 others space being padded. 但是,当我只输入1个字符时,总会有4个其他空格被填充。 How can I avoid the padding, at the same time limiting number of characters? 如何避免填充,同时限制字符数?

JFormattedTextField leads to evil UIs. JFormattedTextField导致邪恶的UI。

The class you want is javax.swing.text.DocumentFilter . 你想要的类是javax.swing.text.DocumentFilter This allows you modify mutations in a chain-of-command style. 这允许您修改命令链样式中的突变。

Instead of a JFormattedTextField, use a plain JTextField. 而不是JFormattedTextField,使用普通的JTextField。 Change the textfield's document to accept only a specific number of characters by setting a custom document. 通过设置自定义文档,将文本字段的文档更改为仅接受特定数量的字符。

Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. 很棒的问题,Swing工具包本身不包含JTextFields的这个功能,这很奇怪。 But, here's a great answer from my Udemy.com course "Learn Java Like a Kid": 但是,这是我的Udemy.com课程“像孩子一样学习Java”的一个很好的答案:

txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) { 
        if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
            e.consume(); 
    }  
});

This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal. 这会将猜测游戏文本字段中的字符数限制为3个字符,方法是重写keyTyped事件并检查文本字段是否已有3个字符 - 如果是,则“消耗”关键事件(e),以便它没有得到正常的处理。

Hope that helps :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM