Java 如何将整数值放入 JLabel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19510198/
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-12 17:52:41  来源:igfitidea点击:

How to put integer value in JLabel?

javaswingjlabel

提问by brainsfrying

I need to display an integer onto JLabel, the following code does not work out well, even with Integer.parse().

我需要在 上显示一个整数JLabel,以下代码效果不佳,即使使用Integer.parse().

How do I rectify it?

我该如何纠正?

JLabel lblTemp = new JLabel("");
lblTemp.setBounds(338, 26, 46, 14);
contentPane.add(lblTemp);

//store int value of item clicked @ JList
int temp = list.getSelectedIndex() + 1;
lblTemp.setText(temp);   // <- problem

采纳答案by Alexis C.

Use String.valueOfmethod :

使用String.valueOf方法:

Returns the string representation of the int argument.

返回 int 参数的字符串表示形式。

lblTemp.setText(String.valueOf(temp));

回答by Jj Tuibeo

lblTemp.setText(String.valueOf(temp));

Your temp is an integer but the type that the setText(...)method accepts is String. You need to convert first your integer to String.

您的 temp 是一个整数,但该setText(...)方法接受的类型是 String。您需要先将整数转换为字符串。

回答by Carlos Salazar

The quick and dirty solution for putting integers in places that expect strings is to do the following:

将整数放在需要字符串的地方的快速而肮脏的解决方案是执行以下操作:

lblTemp.setText(temp + "");

I hope this helps.

我希望这有帮助。

回答by Ashish

setText() takes string as an argument. Use this line to code to convert int to string.

setText() 将字符串作为参数。使用此行代码将 int 转换为 string。

Integer.toString(number)

Hope it helps.

希望能帮助到你。

回答by Murali

If you use Wrapper class Integerinstead of primitive type int then you can get temp.toString()method that automatically convert to string value

如果您使用Wrapper 类 Integer而不是原始类型 int 那么您可以获得自动转换为字符串值的temp.toString()方法

回答by Naveen S

You can Use String.valueOf() or Integer.toString() Methods

您可以使用 String.valueOf() 或 Integer.toString() 方法

lblTemp.setText(String.valueOf(temp));

lblTemp.setText(String.valueOf(temp));

or

或者

lblTemp.setText(Integer.toString(temp));

lblTemp.setText(Integer.toString(temp));