Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To limit the number of characters in JTextField?

Tags:

java

swing

How to limit the number of characters entered in a JTextField?

Suppose I want to enter say 5 characters max. After that no characters can be entered into it.

like image 801
Santosh V M Avatar asked Aug 19 '10 06:08

Santosh V M


People also ask

How do I limit the number of characters in a text field in Java?

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

How do I allow only numbers in JTextField?

txtAnswer. addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e. getKeyCode(); /* Restrict input to only integers */ if (key < 96 && key > 105) e. setKeyChar(''); }; });

How do I make JTextField smaller?

put your jtextfield within a JPanel, now that JPanel is the one which will have large size, but that won't be visible and then you can control the layout of JPanel and hence you can control the size of the jtextfield.

Can you enter more than one line in a JTextField?

Only one line of user response will be accepted. If multiple lines are desired, JTextArea will be needed. As with all action events, when an event listener registers an event, the event is processed and the data in the text field can be utilized in the program.


1 Answers

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)

like image 56
tim_yates Avatar answered Sep 20 '22 01:09

tim_yates