1

I need to display an integer onto JLabel, the following code does not work out well, even with 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
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
brainsfrying
  • 241
  • 1
  • 6
  • 21
  • 1
    1) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Oct 22 '13 at 06:16

6 Answers6

8

Use String.valueOf method :

Returns the string representation of the int argument.

lblTemp.setText(String.valueOf(temp));
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
3
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.

Jj Tuibeo
  • 773
  • 4
  • 18
1

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.

1

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

Integer.toString(number)

Hope it helps.

Ashish
  • 735
  • 1
  • 6
  • 15
1

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

Murali
  • 341
  • 2
  • 7
  • 24
0

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

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

or

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

Naveen S
  • 49
  • 9