Re: Keystroke validation in JTextField

Discussion in 'Java' started by Lew, Oct 1, 2007.

  1. Lew

    Lew Guest

    icogs wrote:
    >> Simple one I hope:


    Please do not multipost.

    It causes answers to appear in only one of the multiple groups to which you
    posted your message. You need to keep the answers together, e.g., by
    cross-posting, or better, by sticking with only one group for your post.

    >> How can I intercept keystrokes to a JTextField so I could, for
    >> example, implement a digit-only text field [question mark omitted in orig.]


    Knute Johnson's answer for the other group who missed it:
    > You don't want to do it that way with JComponents. Use a Document to
    > control those sorts of things. Look at PlainDocument in the docs and
    > see an example below of how to implement a document that only allows
    > upper case letters.
    >
    > //
    > //
    > // UpperCaseDocument
    > //
    > //
    >
    > import java.awt.*;
    > import java.awt.event.*;
    > import javax.swing.*;
    > import javax.swing.text.*;
    >
    > public class UpperCaseDocument extends PlainDocument {
    > int length = 0;
    >
    > public UpperCaseDocument() {
    > }
    >
    > public UpperCaseDocument(int length) {
    > this.length = length;
    > }
    >
    > public void insertString(int offs, String str, AttributeSet a)
    > throws BadLocationException {
    > if (str == null) {
    > return;
    > }
    > if (length > 0)
    > if (str.length() + getLength() > length)
    > str = str.substring(0,length - getLength());
    > char[] upper = str.toCharArray();
    > for (int i = 0; i < upper.length; i++)
    > upper = Character.toUpperCase(upper);
    > super.insertString(offs, new String(upper), a);
    > }
    > }
    Lew, Oct 1, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JustJohn
    Replies:
    6
    Views:
    621
    JustJohn
    Mar 29, 2006
  2. Herb Stull

    Keystroke Count

    Herb Stull, Oct 17, 2003, in forum: ASP .Net
    Replies:
    4
    Views:
    3,338
    Will T
    Oct 22, 2003
  3. Fred
    Replies:
    6
    Views:
    3,329
    pete kirkham
    Aug 2, 2003
  4. =?ISO-8859-1?Q?St=E9phane_St-Pierre?=

    KeyStroke madness

    =?ISO-8859-1?Q?St=E9phane_St-Pierre?=, Sep 19, 2003, in forum: Java
    Replies:
    1
    Views:
    364
    Gerbrand van Dieijen
    Sep 20, 2003
  5. icogs
    Replies:
    0
    Views:
    388
    icogs
    Oct 1, 2007
Loading...

Share This Page