How to limit the number of digits in a JPasswordField in Java?

后端 未结 4 788
轻奢々
轻奢々 2020-12-12 01:20

I have my Java code working in Eclipse but I need to add a few functionnality.

First, how to limit the number of digits that can be entered by the user ? Actually I

4条回答
  •  被撕碎了的回忆
    2020-12-12 01:51

    First, how to limit the number of digits that can be entered by the user ?

    • See this Q&A: How To limit the number of characters in JTextField? As JPasswordField extends from JTextField it should perfectly work.
    • As @nachokk correctly pointed out, working with document filters (like he does in his answer) is a more flexible option. You can read more about it in Concepts: About Documents and Implementing a Document Filter sections of Text Component Features official article.

    Then, how can I play with the size of the JPassword box ? Is there a way to modify it just like a JTextField for example ? Because my line "p1.setPreferredSize(new Dimension(100, 25));" does not seem to really let me modify the size of the box.

    • Don't set fixed sizes when you're working with Swing. See this topic: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?.
    • You can use setColumns(int columns) instead to indicate the preferred size of the text field.
    • See How to Use Password Fields tutorial.

提交回复
热议问题