Solved

Better JTextField

Posted on 1998-08-03
2
272 Views
Last Modified: 2008-02-26
How can I create a JTextField that accepts only a predefined length of characters, or accepts only numbers?
0
Comment
Question by:incah
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 6

Accepted Solution

by:
gadio earned 50 total points
ID: 1230611
incah, add a TextListener to the JTextField, that on every text change event will check the contents of the field. If the contents is not valid, you can undo the last character or beep or whatever. Note that you can use the java.text.NumberFormat to help you with the nunmbers.
0
 

Author Comment

by:incah
ID: 1230612
You mean a DocumentListener. There is no TextListener for a JTextField. Anyway I did it in the following code,but it doesn't work as expected. When the first non-digit character is entered the program that uses the NumberJTextField freezes. But even if it worked I can't find of a nice way to change the content of the field (see method doWork() which removes the entire contents and inserts a new String. There I'm forced to pass null as the third parameter to insertString() because I don't know what else to pass).

import com.sun.java.swing.*;
import com.sun.java.swing.text.*;
import com.sun.java.swing.event.*;

public class NumberJTextField extends JTextField {
      public NumberJTextField() {
            super();
            this.getDocument().addDocumentListener(new MyDocumentAdapter());
      }
      public NumberJTextField(String text) {
            super(checkedString(text));
            this.getDocument().addDocumentListener(new MyDocumentAdapter());
      }
      public NumberJTextField(int columns) {
            super(columns);
            this.getDocument().addDocumentListener(new MyDocumentAdapter());
      }
      public NumberJTextField(String text,int columns) {
            super(checkedString(text),columns);
            this.getDocument().addDocumentListener(new MyDocumentAdapter());
      }
      public NumberJTextField(Document doc,String text,int columns) {
            super(doc,checkedString(text),columns);
            this.getDocument().addDocumentListener(new MyDocumentAdapter());
      }
      private static String checkedString(String text) {
            if (text==null || text.equals(""))
                  return(text);
            int len=text.length();
            StringBuffer out=new StringBuffer(len);
            char c;
            for (int i=0;i<len;i++) {
                  c=text.charAt(i);
                  if (c>='0' && c<='9')
                        out.append(c);
            }
            return(out.toString());
      }
      public void setText(String text) {
            super.setText(checkedString(text));
      }

      class MyDocumentAdapter implements DocumentListener {
            public void insertUpdate(DocumentEvent e) {
                  doWork(e);
            }
            public void removeUpdate(DocumentEvent e) {
            }
            public void changedUpdate(DocumentEvent e) {
                  doWork(e);
            }
            private void doWork(DocumentEvent e) {
                  Document doc=e.getDocument();
                  int len=doc.getLength();
                  if (len>0) {
                        try {
                              String text=doc.getText(0,len),
                                                                               out=checkedString(text);
                              if (!text.equals(out)) {
                                    doc.remove(0,len);
                                    doc.insertString(0,out,null);
                              }
                        } catch(BadLocationException ble) {
                        }

                  }
            }
      }

}

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
configure dependency in POM for new database 3 44
hibernate example for saving data 19 74
spring jars download 1 52
servlet and mdb, jms error 1 57
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question