• Post Reply Bookmark Topic Watch Topic
  • New Topic

To make JLabel get the value from JSlider  RSS feed

 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made JLabel and I would like to make it get the value from JSlider. As JSlider changes, the JLabel should change also. How Can I do it?

I wrote but it just gets the initial value of slider and it doesn't change as slider value changes.

What could be the problem here?
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you put any Listeners on the JSlider?
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No I thought about that, but I'm not sure how to write it. Any hint...?
 
Rob Spoor
Sheriff
Posts: 20898
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the methods JSlider has that start with "add" and end with "Listener". For each create an implementation that only prints the event. You should then be able to choose the one you need.

Don't forget that most component classes inherit listener methods from their super classes. But in this case you don't need to check those of JComponent; those defined in JSlider are all you'll need.
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been looking and I wrote this:



It works fine, it prints numbers while I move the slider. But when I tried to put it in JLabel, it reported error since it expected string and found integer. I was intending to write toString() but it doesn't recognize it. How should I do this conversion of types?
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What sort of value are you getting? Integer, integer or int? Look in the Integer class and the String class for methods to convert ints to Strings.
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Value is int.

I have succeed to solve the problem.

Here is how it looks:



It was only necessary to add here setting text to label so it would change as slider value changes. Also, label text should be initialized same as slider's position when it starts to run.

Thank you guys for interesting

Greetings for all!
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!