Search code examples
javaswingjtextfield

Does setText() method always set value to a string?


Does the method setText() always set to a string? If we want to set a Double value to the text field, hows it done?


Solution

  • setText() only accepts a String. In order to insert a double, you can just concatenate the double to a string:

    double someDouble = 2.5;
    yourJTextField.setText("" + someDouble);
    

    Notice that the double displays as 2.5. To format the double, see String.format().


    Edit, 5 years later

    I agree with the other answers that it is cleaner to use Double.toString(someDouble) to do the conversion.