aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Limited Document JTextField" Watch "Limited Document JTextField" New topic
Author

Limited Document JTextField

pindur pandur
Greenhorn

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) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(param, str, attributeSet);
}


}
pindur pandur
Greenhorn

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
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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!
 
 
subject: Limited Document JTextField