Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Limited Document JTextField

 
pindur pandur
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's move this to the Swing/AWT forum where it is more likely to attract the attention of the right people.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic