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.
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.
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
Related Topics
Spring Boot @Responsebody Doesn't Serialize Entity Id
Is Jdk "Upward" or "Backward" Compatible
Why Do Many Collection Classes in Java Extend the Abstract Class and Implement the Interface as Well
What Does It Mean to Program to an Interface
Write a File in Hdfs with Java
Best Way to Format Multiple 'Or' Conditions in an If Statement
Safe String to Bigdecimal Conversion
What Is the Breakdown for Java's Lambda Syntax
How to Open a File with the Default Associated Program
How to Sort Date Which Is in String Format in Java
Get All of the Classes in the Classpath
Take N Random Elements from a List<E>
Java: "Final" System.Out, System.In and System.Err
Converting JSON to Xls/CSV in Java
How to Use Regex in String.Contains() Method in Java
Why Can't I Use a Type Argument in a Type Parameter with Multiple Bounds