This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Limited Document JTextField Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Limited Document JTextField" Watch "Limited Document JTextField" New topic

Limited Document JTextField

pindur pandur

Joined: Oct 26, 2005
Posts: 8
I have a JTextField that only lets the user enter 20 characters. But the problem is, it doesn't let the user press enter. Here is the code. How can I change it so it will let the user press enter after typing in 20 or less characters?
import javax.swing.text.*;

public class LimitedDocument extends PlainDocument {

private int maxLen = -1;
/** Creates a new instance of LimitedPlainDocument */

public LimitedDocument(int maxLen) {

this.maxLen = maxLen;

public void insertString(int param, String str, AttributeSet attributeSet)
throws BadLocationException {
if (str != null && maxLen > 0 && this.getLength() + str.length() > maxLen) {
super.insertString(param, str, attributeSet);

pindur pandur

Joined: Oct 26, 2005
Posts: 8
My problem is that when the user presses enter in this JTextField nothing happens. If I set a key listener to listen for VK_ENTER what is the action that I want to happen? Set text and yield focus? The action happens if I move focus off the field. I want it to happen with user pressing enter. I'm not sure how to do it. Any suggestions?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Let's move this to the Swing/AWT forum where it is more likely to attract the attention of the right people.

[Jess in Action][AskingGoodQuestions]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
It's unclear what you are saying -- whether or not a JTextField has a custom
document has nothing to do with its behavior when you press VK_ENTER. If
you want a JTextField to react to enter being pressed, register an ActionListener
with the component.

There is no emoticon for what I am feeling!
I agree. Here's the link:
subject: Limited Document JTextField
It's not a secret anymore!