简体   繁体   English

Java jLabel.setText()方法不使用String重载

[英]Java jLabel.setText() method overloading not with String

In a jLabel component, say I have this codes, 在jLabel组件中,假设我有这个代码,

JLabel jLabel = new JLabel();
jLabel.setText( 123 ) ;

It generates error. 它会产生错误。 But writing this, 但写这个,

jLabel.setText( 123 + "" ) ;

force to int part to be a string. 强制将int部分转换为字符串。 But I don't think writing int like that way is a good idea! 但我不认为像这样写int是个好主意! Does this method has any overloaded siblings grasping not a String? 这个方法是否有任何重载的兄弟姐妹不是一个字符串?

Not much you can do here, setText only takes a String parameter. 你在这里做的不多, setText只接受一个String参数。 Alternatively, you could do jLabel.setText(Integer.toString(123)) , if you find this more readable. 或者,您可以执行jLabel.setText(Integer.toString(123)) ,如果您发现它更具可读性。

As for 123 + "" part, whenever you add some variables and at least one of them is a String , the compiler will automatically call toString on the others and will concatenate all the strings. 至于123 + ""部分,每当你添加一些变量并且其中至少有一个是String ,编译器会自动调用其他变量上的toString并连接所有字符串。 somevar + "" (empty string) is a quick way of calling somevar.toString() . somevar + "" (空字符串)是一种调用somevar.toString()的快捷方式。

The compiler is correct. 编译器是正确的。 You are passing a number to a method that wants the string. 您正在将数字传递给需要该字符串的方法。 The reason the second method works is that the jvm is taking the number and the string, and adding them together, which returns a string, which is why it works. 第二种方法工作的原因是jvm取数字和字符串,并将它们加在一起,返回一个字符串,这就是它工作的原因。 Your other option is to do something Integer.toString(123); 你的另一个选择是做一些Integer.toString(123);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM