I've been writing a very basic musicplayer in Java for a school project, and I wanted to add a little sazz by implementing a volume slider. Basically, I read step by step how to do it, and it does work, but there is one element that I frankly don't understand, and that is the
(JSlider)event.getSource();
method. What I dont't understand is what seems to be casting. Why do I need to cast the event.getSource() to JSlider? And how can I even, since ChangeEvent and JSlider do not have a (to my understanding, at least) sub-class/superclass relationship?
Here is the method in full:
public void stateChanged(ChangeEvent event)
{
JSlider source = (JSlider)event.getSource();
int volume = source.getValue();
setVolume(volume);
}
The method signature is
public Object getSource()
Since it returns Object, it has to be casted to a JSlider to assign it to a JSlider variable. Everything is a subtype of Object; the compiler does not know that the returned Object is a JSlider.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With