Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 460
  • Last Modified:

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
0
AntoniRyszard
Asked:
AntoniRyszard
  • 14
  • 11
  • 9
  • +3
1 Solution
 
CEHJCommented:
Easier to test after all entered
0
 
objectsCommented:
you can use a custom Document with your text field that does the test
0
 
objectsCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
AntoniRyszardAuthor Commented:
do you have any examples of the custom document?

Thanks
0
 
AntoniRyszardAuthor Commented:

How would I link the  IntegerDocument  class to the textfields?

Thanks
0
 
objectsCommented:
to use that with your field with:

tf.setDocument(new IntegerDocument());
0
 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
JohnnyAffaCommented:
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
 
AntoniRyszardAuthor Commented:
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
 
CEHJCommented:
>>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
 
JohnnyAffaCommented:
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
 
wolfcCommented:
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
 
AntoniRyszardAuthor Commented:
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
 
AntoniRyszardAuthor Commented:

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

>>To use the object would this be correct?

Yes and yes

0
 
AntoniRyszardAuthor Commented:

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

Thanks
0
 
CEHJCommented:
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
 
AntoniRyszardAuthor Commented:
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
 
CEHJCommented:
If you put the buttons in a GridLayout with one column, they'll all be the same width
0
 
CEHJCommented:
A kludgy way without changing your layout is to pad the captions with spaces to the length of the longest caption ;-)
0
 
objectsCommented:
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
 
objectsCommented:
> 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
 
wolfcCommented:
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
 
objectsCommented:
> IMHO the JFormattedTextField approach is the easiest

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

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

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

0
 
AntoniRyszardAuthor Commented:

Thanks for replying.

Nice to see a lively debate.

0
 
objectsCommented:
I provide no warranty for the mod he made to my class (and it doesn't meet your spec anyway) ;)
0
 
AntoniRyszardAuthor Commented:
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
 
CEHJCommented:
>>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
 
CEHJCommented:
8-)
0
 
AntoniRyszardAuthor Commented:
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
 
CEHJCommented:
OK ;-)
0
 
wolfcCommented:
Well if we're continuing the discussion anyway. :-)

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

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

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

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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 14
  • 11
  • 9
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now