- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we limit the number of characters inside a JTextField in Java?
A JTextFeld is one of the most important components that allow the user to an input text value in a single line format. We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.
In the below example, we can implement the logic by using a PlainDocument class, hence we can allow a user to enter a maximum of 10 characters, it doesn't allow if we enter more than 10 characters.
Example
import java.awt.*; import javax.swing.*; import javax.swing.text.*; class JTextFieldLimit extends PlainDocument { private int limit; JTextFieldLimit(int limit) { super(); this.limit = limit; } JTextFieldLimit(int limit, boolean upper) { super(); this.limit = limit; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) return; if ((getLength() + str.length()) <= limit) { super.insertString(offset, str, attr); } } } public class JTextFieldLimitTest extends JFrame { JTextField textfield; JLabel label; public static void main(String[]args){ new JTextFieldLimitTest().GUI(); } public void GUI() { setLayout(new FlowLayout()); label = new JLabel("max 10 chars"); textfield = new JTextField(15); add(label); add(textfield); textfield.setDocument(new JTextFieldLimit(10)); setSize(350,300); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } }
Output
- Related Articles
- How can we implement a rounded JTextField in Java?
- How can we add padding to a JTextField in Java?
- How can we make JTextField accept only numbers in Java?
- How can we implement cut, copy and paste functionality of JTextField in Java?
- Can we save content from JTextField to a file in Java?
- How can we display the line numbers inside a JTextArea in Java?
- How can we disable the cell editing inside a JTable in Java?
- How to limit the number of characters entered in a textarea in an HTML form?
- How to limit the number of characters allowed in form input text field?
- How can we enter characters as a BINARY number in MySQL statement?
- Can we define a class inside a Java interface?
- How can we add/insert a JCheckBox inside a JTable cell in Java?
- Can we define an enum inside a class in Java?
- Can we define an enum inside a method in Java?
- Can we define an interface inside a Java class?

Advertisements