Solved

Testing JTextField:

Posted on 2004-08-01
42
454 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
ID: 11689782
Easier to test after all entered
0
 
LVL 92

Expert Comment

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

Expert Comment

by:objects
ID: 11689798
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:AntoniRyszard
ID: 11689801
do you have any examples of the custom document?

Thanks
0
 

Author Comment

by:AntoniRyszard
ID: 11689817

How would I link the  IntegerDocument  class to the textfields?

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 11689821
to use that with your field with:

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

Expert Comment

by:Mayank S
ID: 11690848
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11692113
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
ID: 11692572
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
ID: 11692762
>>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
ID: 11692855
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
ID: 11693339
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
ID: 11696029
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
ID: 11696078

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
ID: 11696130
>>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
ID: 11696612

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
ID: 11696835
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
ID: 11697150
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
ID: 11697304
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
ID: 11697320
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
ID: 11699298
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
 
LVL 92

Expert Comment

by:objects
ID: 11699331
> 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
ID: 11701730
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
ID: 11701768
> IMHO the JFormattedTextField approach is the easiest

i actually agree with you :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11701970
>>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
ID: 11702018
both approaches work fine
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11702030
Wrong ;-)
0
 

Author Comment

by:AntoniRyszard
ID: 11708031
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
ID: 11708097

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
ID: 11710408
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
ID: 11710748

Thanks for replying.

Nice to see a lively debate.

0
 
LVL 92

Expert Comment

by:objects
ID: 11710777
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
ID: 11710868
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
ID: 11715952
>>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
ID: 11715965
8-)
0
 

Author Comment

by:AntoniRyszard
ID: 11716271
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
ID: 11716347
OK ;-)
0
 
LVL 1

Expert Comment

by:wolfc
ID: 11716379
Well if we're continuing the discussion anyway. :-)

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

Author Comment

by:AntoniRyszard
ID: 11716458

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
ID: 11718076
Create a class which implements DocumentFilter and then doc.setDocumentFilter(myFilter);
0
 

Author Comment

by:AntoniRyszard
ID: 11718618

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

Thanks
0
 
LVL 1

Expert Comment

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

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 63
Arrays.asList  VS  ArrayList 4 71
Way to decrease size of apk file 9 87
Problem to Alipay 10 44
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…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

829 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