Link to home
Start Free TrialLog in
Avatar of AntoniRyszard
AntoniRyszard

asked on

Testing JTextField:

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
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Easier to test after all entered
you can use a custom Document with your text field that does the test
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();
          }
     
     }
}
Avatar of AntoniRyszard
AntoniRyszard

ASKER

do you have any examples of the custom document?

Thanks

How would I link the  IntegerDocument  class to the textfields?

Thanks
to use that with your field with:

tf.setDocument(new IntegerDocument());
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


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
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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;
    }
}
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();
      }
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

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
>>Would creating an object extending the plain document, not the best approach?

>>To use the object would this be correct?

Yes and yes


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

Thanks
You'd better ask them ;-) In the view of two of us here (take a look at the rankings) it's the best way
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
If you put the buttons in a GridLayout with one column, they'll all be the same width
A kludgy way without changing your layout is to pad the captions with spaces to the length of the longest caption ;-)
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
> 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.
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.
> IMHO the JFormattedTextField approach is the easiest

i actually agree with you :)
>>i actually agree with you :)

That's ironic, since it doesn't work for similar reasons to the code you posted ;-)
both approaches work fine
Wrong ;-)
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

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
Hmm, after CEHJ says to test after all entered, he then copies my suggested approach for checking while entering.
Go figure :-D


Thanks for replying.

Nice to see a lively debate.

I provide no warranty for the mod he made to my class (and it doesn't meet your spec anyway) ;)
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.
>>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?
8-)
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) {
   }
}

}
OK ;-)
Well if we're continuing the discussion anyway. :-)

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

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

Or does the DocumentFilter not involve creating a new class?

Thanks
Create a class which implements DocumentFilter and then doc.setDocumentFilter(myFilter);

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

Thanks
Then it would also be usable in a StyledDocument.
It's a nice to have.