Solved

Testing JTextField:

Posted on 2004-08-01
42
455 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
[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
  • 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jsp insert to database example 2 64
Detect Closed Loops (circles, figure-8s, etc) in PNG Images 6 77
jmss example java 2 33
Java basic valueOf question 1 34
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…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

726 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