Java setText() 方法是否总是将值设置为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22116906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:42:51  来源:igfitidea点击:

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

javaswingjtextfield

提问by Toms

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

方法 setText() 是否总是设置为字符串?如果我们想给文本字段设置一个 Double 值,怎么做?

采纳答案by MC Emperor

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

setText()只接受一个String. 为了插入 a double,您可以将 double 连接到一个字符串:

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

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

请注意,double 显示为2.5。要格式化双精度,请参阅String.format()



Edit, 5 years later

5年后编辑

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

我同意其他答案,即使用Double.toString(someDouble)它进行转换更清洁。

回答by JB Nizet

You transform the Double to a string first:

您首先将 Double 转换为字符串:

textField.setText(myDouble.toString());

At the risk of contradicting the other answers here, a primitive double should, IMHO, be transformed to a String using Double.toString(d)or String.valueOf(d), which expresses the intent more clearly (and is more efficient) than concatenation.

冒着与此处其他答案相矛盾的风险,恕我直言,原始 double 应该转换为 String 使用Double.toString(d)or String.valueOf(d),这比串联更清晰(并且更有效)表达意图。

回答by camickr

If you have an actual Double object then you can use:

如果您有一个实际的 Double 对象,那么您可以使用:

textField.setText( doubleValue.toString() );

Or, if you have a double primitive you can use:

或者,如果您有一个双原语,您可以使用:

textField.setText( doubleValue + "" );