How To limit the number of characters in JTextField?
http://www.rgagnon.com/javadetails/java-0198.html
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
public class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
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);
}
}
}
Then
import java.awt.*;
import javax.swing.*;
public class DemoJTextFieldWithLimit extends JApplet{
JTextField textfield1;
JLabel label1;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
getContentPane().add(label1);
getContentPane().add(textfield1);
textfield1.setDocument
(new JTextFieldLimit(10));
}
}
(first result from google)
Limit number of characters in JTextField
JFormattedTextField
leads to evil UIs.
The class you want is javax.swing.text.DocumentFilter
. This allows you modify mutations in a chain-of-command style.
How to restrict the JTextField to a x number of characters
You should use a DocumentFilter as per this tutorial. For example:
import javax.swing.*;
import javax.swing.text.*;
public class JTextFieldLimit2 extends JPanel{
JTextField textfield = new JTextField(5);
public JTextFieldLimit2() {
PlainDocument doc = (PlainDocument) textfield.getDocument();
doc.setDocumentFilter(new TextLengthDocFilter(3));
add(textfield);
}
private class TextLengthDocFilter extends DocumentFilter {
private int maxTextLength;
public TextLengthDocFilter(int maxTextLength) {
this.maxTextLength = maxTextLength;
}
private boolean verifyText(String text) {
return text.length() <= maxTextLength;
}
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
String oldText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(oldText);
sb.insert(offset, string);
if (verifyText(sb.toString())) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
Document doc = fb.getDocument();
String oldText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(oldText);
sb.replace(offset, offset + length, text);
if (verifyText(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
Document doc = fb.getDocument();
String oldText = doc.getText(0, doc.getLength());
StringBuilder sb = new StringBuilder(oldText);
sb.replace(offset, offset + length, "");
if (verifyText(sb.toString())) {
super.remove(fb, offset, length);
}
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("JTextFieldLimit2");
frame.getContentPane().add(new JTextFieldLimit2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Limit character input in jtextfield or area
I would use javax.swing.text.Document
You can initiate it like:
public static Document createTextDocument(int maxLength){
return new TextDocument(maxLength);
}
...
Document document = createTextDocument(5); // limit to 5 chars
textField1.setDocument(document);
document = createTextDocument(10); // limit to 10 chars
textField2.setDocument(document);
Here is custom TextDocument
class:
public class TextDocument extends PlainDocument{
private static final long serialVersionUID = 1L;
private int maxLength = Integer.MAX_VALUE;
TextDocument(){}
TextDocument(int maxlength){this.maxLength=maxlength;}
public void setMaxLength(int maxLength) {
if (maxLength < 0)
throw new IllegalArgumentException("maxLength<0");
this.maxLength = maxLength;
}
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (validateLength(offset, str) == false)
return;
super.insertString(offset, str, attr);
}
private boolean validateLength(int offset, String toAdd) {
String str_temp;
//String str_text = "";
String str1 = "";
String str2 = "";
try {
str1 = getText(0, offset);
str2 = getText(offset, getLength() - offset);
} catch (Exception e) {
e.printStackTrace();
}
str_temp = str1 + toAdd + str2;
if (maxLength < str_temp.length()) {
beep();
return false;
} else
return true;
}
private void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
}
Hope it will help
JTextField: How to limit the number of characters?
simply change your current remove method:
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException
{
fb.insertString(offset, "", null);
}
for this one:
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException
{
fb.remove(offset, length);
}
it should now work.
Related Topics
Regex Look-Behind Without Obvious Maximum Length in Java
What's the Difference Between Session.Persist() and Session.Save() in Hibernate
Add Custom CSS to HTML Code with Jsoup
Java.Lang.Illegalmonitorstateexception: Object Not Locked by Thread Before Wait()
Send Sms Until It Is Successful
Android Days Between Two Dates
How to Draw a Filled Triangle in Android Canvas
Get a JSON Object from a Http Response
Android.App.Application Cannot Be Cast to Android.App.Activity
How to Pass Values Between a Dialog and an Activity
Right Way to Implement Equals Contract
How to Capitalize the First Letter of a String in Java
How to Clear the (Css) Visited History of an Android Webview
Import Google Play Services Library in Android Studio
Java Doesn't Work with Regex \S, Says: Invalid Escape Sequence
How to Draw Circle by Canvas in Android