Solved

Testing JTextField:

Posted on 2004-08-01
42
447 Views
Last Modified: 2008-02-01
Hello,

I am writing a dialog box which asks the user for 3 numbers. The dialog also includes a submit button.

In the program I need to test the numbers entered are been 0 and 100. And wondered if there was any method of testing the value as they are entered?

Or if it better to enter the values and when the user clicks submit, then test the numbers and display an error message if needs?

Thanks
0
Comment
Question by:AntoniRyszard
  • 14
  • 11
  • 9
  • +3
42 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Easier to test after all entered
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
you can use a custom Document with your text field that does the test
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
heres an example that just allow integers to be entered (which is probably useful whichever way you go anyway)

public class IntegerDocument extends PlainDocument
{
     public IntegerDocument()
     {
          super();
     }

     public void insertString(int offset, String s, AttributeSet attributeSet)
          throws BadLocationException
     {
          try
          {
               Integer.parseInt(getText(0, offset) + s + getText(offset, getLength()-offset));
               super.insertString(offset, s, attributeSet);
          }
          catch (Exception ex)
          {
               Toolkit.getDefaultToolkit().beep();
          }
     
     }
}
0
 

Author Comment

by:AntoniRyszard
Comment Utility
do you have any examples of the custom document?

Thanks
0
 

Author Comment

by:AntoniRyszard
Comment Utility

How would I link the  IntegerDocument  class to the textfields?

Thanks
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
to use that with your field with:

tf.setDocument(new IntegerDocument());
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
0
 
LVL 3

Expert Comment

by:JohnnyAffa
Comment Utility
try

TextField textbox = new TextField();


// after button has been clicked

try
{
   int value = Integer.parseInt(textbox.getText());
}
catch (Exception a)
{
   System.out.println("Error, invalid value");
}

the above code ensures that ONLY integer values are entered, this also includes negative ints as well, you could add

int value = Integer.parseInt(textbox.getText());

if ( value > 0 )
// process


0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thank you for replying.

My dialog has three textfields, I would like them to accept only whole numbers, no decimal values or minus values or chars.

Could I write just one class which extends PlainDocument, and use this class with all the textfields?

And if an incorrect value was entered, it was ignored rather than displaying an error. Would this possible?

Thanks
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
Comment Utility
>>no decimal values or minus values or chars

The code posted previously will not work in that case, as it will accept pasted negative numbers. Change the appropriate method to:


      public void insertString(int offset, String s, AttributeSet attributeSet)
                   throws BadLocationException {
            try {
                  String candidate = getText(0, offset) + s + getText(offset, getLength() - offset);
                  if (candidate.matches("\\d+")) {
                        super.insertString(offset, s, attributeSet);
                  }
            }
            catch (Exception ex) {
                  /* ignore */
            }
      }


>>Could I write just one class which extends PlainDocument, and use this class with all the textfields?

Yes, just set a new instance of the above as the document for each field

>>And if an incorrect value was entered, it was ignored rather than displaying an error. Would this possible?

It will be ignored
0
 
LVL 3

Expert Comment

by:JohnnyAffa
Comment Utility
objects, whats with the plaindocument object?

anton

JButton button = new JButton();
button.addMouseListener(this);


JTextField textbox[] = new JTextField();

for ( int index = 0; index < textbox.length; index++ )
{
   textbox[index] = new JTextField();
// set whatever else you need to for each textbox that is common to all of them
}

// assuming youre implementing MouseListener

public void mouseClicked(MouseEvent mouse)
{
   boolean value1 = this.isValid(textbox[0].getText());
   boolean value2 = this.isValid(textbox[1].getText());
   boolean value3 = this.isValid(textbox[2].getText());

// if all 3 are valid then process

    if ( value1 == true && value2 == true && value3 == true )
    {
           int val1 = Integer.parseInt(textbox[0].getText());
           int val2 = Integer.parseInt(textbox[1].getText());
           int val3 = Integer.parseInt(textbox[2].getText());

          // comput them now
     }
}

private boolean isValid(String textbox_value)
{
   try
   {
          int value1 = Integer.parseInt(textbox_value);

          return ( value1 > 0 ) ? true : false;
   }
   catch (Exception a)
  {
           return false;
    }
}
0
 
LVL 1

Expert Comment

by:wolfc
Comment Utility
For Java 1.4 and up:

      public static void main(String[] args) {
            JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            Format fmt = NumberFormat.getIntegerInstance();
            final JFormattedTextField txt = new JFormattedTextField(fmt);
            frame.getContentPane().add(txt);
            
            txt.addActionListener(
                  new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                              System.out.println("value = " + txt.getValue());
                        }
                  }      
            );
            
            frame.pack();
            
            frame.show();
      }
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Hello,

Would creating an object extending the plain document, not the best approach?

To use the object would this be correct?

tf.setDocument(new IntegerDocument());
tf.addActionListener(this);

Thanks
0
 

Author Comment

by:AntoniRyszard
Comment Utility

I meant is using the plaindocument the best approach, taking into account I was hoping to test the values as they were typed.

To be sure the value entered is a whole number, not a decimal number or minus value or char.

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>Would creating an object extending the plain document, not the best approach?

>>To use the object would this be correct?

Yes and yes

0
 

Author Comment

by:AntoniRyszard
Comment Utility

Why do you think the other members do not recommend using an object extending the plain document?

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You'd better ask them ;-) In the view of two of us here (take a look at the rankings) it's the best way
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thank you for replying.

Could I ask finally,

My program displays a column of buttons using the box layout.

The text names in the buttons are all different sizes, and therefore when diaplayed the column of buttons are also different sizes.

Is there any java function, so I could even the buttons lengths, and still center the text in the middle?

Thanks again
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
If you put the buttons in a GridLayout with one column, they'll all be the same width
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
A kludgy way without changing your layout is to pad the captions with spaces to the length of the longest caption ;-)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
CEHJ> Easier to test after all entered

CEHJ> In the view of two of us here (take a look at the rankings) it's the best way

No wonder you confuse people :D
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 92

Expert Comment

by:objects
Comment Utility
> Is there any java function, so I could even the buttons lengths, and still center the text in the middle?

set the preferred/maximum size as appropriate.
0
 
LVL 1

Expert Comment

by:wolfc
Comment Utility
CEHJ> You'd better ask them ;-) In the view of two of us here (take a look at the rankings) it's the best way

Hey, give us newbies a chance :-)

IMHO the JFormattedTextField approach is the easiest, but gives the least eye candy.
The Document approach is nicer to see, but needs more code.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> IMHO the JFormattedTextField approach is the easiest

i actually agree with you :)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>i actually agree with you :)

That's ironic, since it doesn't work for similar reasons to the code you posted ;-)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
both approaches work fine
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Wrong ;-)
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Thanks for replying.

I tried writing a class which extends the plaindocument. This works fine to ignore the char values, and minus numbers.

Not to sure which approach, I will take to even the button lengths.

Thanks
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Just finally, if I wanted to set an initial value to a textfield.

Would it be:

tf = new JTextField(10);
tf.setDocument(new IntegerDocument());
tf.addActionListener(this);
tf = 1;

Thanks
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Hmm, after CEHJ says to test after all entered, he then copies my suggested approach for checking while entering.
Go figure :-D

0
 

Author Comment

by:AntoniRyszard
Comment Utility

Thanks for replying.

Nice to see a lively debate.

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
I provide no warranty for the mod he made to my class (and it doesn't meet your spec anyway) ;)
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Hello,

I added the object which extends the plaindocument to the textfields. This prevents decimal numbers being entered, also minus values and chars. And seems to work.

Out of the 3 textfields I needed to test only one field had a value between 1 and a 100. So I decided to test this when the submit button is clicked.

I think the number of if statements are reduced though, knowing the values can only be whole numbers.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>he then copies my suggested approach for checking while entering

It *is* probably better to have a custom document. So i changed my mind ...

>>I provide no warranty for the mod he made to my class

LOL - the mod was made because the original didn't work properly for the reason i already mentioned ;-)

>>This prevents decimal numbers being entered, also minus values and chars. And seems to work.

Can you show us which code you're using?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0
 

Author Comment

by:AntoniRyszard
Comment Utility
Here's the class, which I then linked to the textfields as was described.

public class IntegerDocument extends PlainDocument{

public IntegerDocument(){
   super();
}

public void insertString(int offset, String s, AttributeSet attributeSet)throws BadLocationException {
   try {
       String candidate = getText(0, offset) + s + getText(offset, getLength() - offset);
      if (candidate.matches("\\d+")) {
         super.insertString(offset, s, attributeSet);
      }
   }
   catch (Exception ex) {
   }
}

}
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
OK ;-)
0
 
LVL 1

Expert Comment

by:wolfc
Comment Utility
Well if we're continuing the discussion anyway. :-)

It's better to use a DocumentFilter for that job.
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Do you mean creating an class which extends DocumentFilter rather than the PainDocument.

Or does the DocumentFilter not involve creating a new class?

Thanks
0
 
LVL 1

Expert Comment

by:wolfc
Comment Utility
Create a class which implements DocumentFilter and then doc.setDocumentFilter(myFilter);
0
 

Author Comment

by:AntoniRyszard
Comment Utility

Could I ask what advantages there are in using the DocumentFilter, rather than PlainDocument?

Thanks
0
 
LVL 1

Expert Comment

by:wolfc
Comment Utility
Then it would also be usable in a StyledDocument.
It's a nice to have.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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 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…
The viewer will learn how to implement Singleton Design Pattern in Java.

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now