开发者

Java jLabel.setText() method overloading not with String

In a jLabel component, say I have this codes,

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

It generates error. But writing this,

jLabel.setText( 123 + "" ) ;

force to int part to be a string. But I don't think w开发者_JS百科riting int like that way is a good idea! Does this method has any overloaded siblings grasping not a String?


Not much you can do here, setText only takes a String parameter. Alternatively, you could do jLabel.setText(Integer.toString(123)), if you find this more readable.

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. somevar + "" (empty string) is a quick way of calling 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. Your other option is to do something Integer.toString(123);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜