Link to home
Start Free TrialLog in
Avatar of Samooramad
Samooramad

asked on

textfield for integer or string

Hi experts,

I need code for the following:
I have a textfield and two buttons. One button should be expect an integer from the text field (between 1-99) and when pressed it changes an integer variable.
the other button should expect a String and then change the "name" variable

thanks


also if anyone can help me with this question I accidently forgot to place it in the java topic area:
https://www.experts-exchange.com/questions/21154053/changing-an-option-pane.html

thanks everyone
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium 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
Sorry:

button1.addActionListener( new ActionListener() {
   public void actionPerformed(ActionEvent evt) {
       try {
          integerVariable = (Integer.valueOf(textField.getText())).intValue();
       } catch (NuberFormatException ex) { }
   }
});
SOLUTION
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
SOLUTION
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
Allow me to correct:

1)
  void jButton4_actionPerformed(ActionEvent e)
  {
     try {                                                  // <<<<<<<< try/catch needed
         int thisVal = Integer.parseInt(jTextField1.getText());
         if( thisVal >= 1 && thisVal <= 99)    // <<<<<<  && instead of ||
            myValu = thisVal;
     } catch (NumberFormatException ex) {
     }
  }

  Remark: I don't see the added value compared with my previous comment


2)
If you want to check if the string only contains A-Z, a-z, spaces and dots, you can better do this:

void jButton5_actionPerformed(ActionEvent e) {

    if ( jTextField1.getText().matches("([A-Za-z \\.])+?") )
      name = jTextField1.getText();
}

That's the power of regular expressions!
Avatar of Naeemg
Naeemg

Thanks zzynx  for correcting my mistakes.
Avatar of Samooramad

ASKER

thanks both of you. I'm working on it.. will get back to you
excelent help as always zzynx :)
thanks Naeemg for your help also.. I forgot I need to check for letters and spaces :)
hey if you guys have a little time please help with the question I mentioned above.. Its driving me nutts :)
thanks