1

I can not find a way to replace an integer. I intend to take an integer from a text field and replace it. I have not a code, but I will write something to make myself understood.

int a = 1500;
JTextField tf = new JTextField();

from this JTextField I would like to take the content number and replace int. Could you help me?

Ludovico
  • 31
  • 4
  • You may be interested by [this](https://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers) – vincrichaud Jun 19 '18 at 08:46

2 Answers2

1

You may get value of JTextField() by using getText() method and set for the same by using setText("value")

try
{
    int a = 1500;
    JTextField tf = new JTextField();
    int value = Integer.parseInt(tf.getText());
    if( value > 0){
       jt.setText(String.valueOf(a)); 
    }
}
catch(Exception e)
{
 //handle exception here
}
Mr. Roshan
  • 1,777
  • 13
  • 33
0

First check whether tf is instantiated and it has a content, then parse the Integer out of the String.

if(tf != null && tf.getText().length > 0){
    a = Integer.parseInt(tf.getText());
}
  • You're welcome. :) Please, mark this answer as solution, if it helped you. –  Jun 19 '18 at 08:32
  • 1
    If you want to check things, then add a Try-catch block around the `parseInt()` method to handle the case the text can't be converted to `int` (for example "aa" can't be converted to an `int`). In this case it throws a `NumberFormatException` – vincrichaud Jun 19 '18 at 08:38