7

I am trying to get Integer values from my jtextfield but not able to it is showing incompatible datatypes required int found string. Is there some other way of writing my code is as follows and i want to get only integer values

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = jTextField3.getText();
            jTextField1.setText(numberToWord(jml));

        }
    }
2
  • 3
    1) Consider using a JSpinner with SpinnerNumberNodel instead. 2) Both JTextField & JSpinner have better listeners than MouseListener available - they are ActionListener & ChangeListener respectively. Commented Jan 5, 2013 at 6:35
  • See also this answer related to JSpinner. The models make it a versatile and intuitive (for the user) component. Commented Jan 5, 2013 at 6:55

2 Answers 2

12

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Be sure to handle NumberFormatException, which parseInt() will throw if the use inputs something non-numeric.
Yes, it is a checked exception so it will force the user to handle it. I have left some space for OP to think over.
I think trim() would help here as well.
4

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.