Solved

Better JTextField

Posted on 1998-08-03
2
270 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
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Java Loop 6 59
servlet doXXX methods 3 48
Can anyone please tell me why i can not find ID  investorCoolGrid inside the jsp page? 1 19
login form jsp example 2 24
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

786 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