Why does this method need casting?

I wrote a very simple Java music player for a school project, and I wanted to add a little bit of sazza by implementing the volume slider. Basically, I read step by step how to do it, and it works, but there is one element that, frankly, I don’t understand, and that’s

(JSlider)event.getSource(); 

method. What I do not understand is what seems to be throwing. Why do I need to pass event.getSource () to JSlider? And how can I, since ChangeEvent and JSlider do not (in my opinion, at least) have a subclass / superclass relationship?

Here is the complete method:

public void stateChanged(ChangeEvent event)
    {
        JSlider source = (JSlider)event.getSource();

        int volume = source.getValue();

        setVolume(volume);
    }
+4
source share
5 answers

Method signature

public Object getSource ()

Object, JSlider, JSlider. ; , JSlider.

+4

event , source.

source :

event.getSource();

, , , JSlider. getSouce() , Object, , , , , ClassCastException.

+3

, . , :

Object getSource()

getSource() Object ( ), :

// listener method
public void stateChanged( ChangeEvent evt )
{
  JSlider source;

  source = (JSlider)evt.getSource();
  . . . .
}

, , .

+1

ChangeEvent ( , ChangeEvent). , JSlider, JSlider.

0

, (Swing Components).

, .

If you did not pass JSlider, you could not use the method getValue().

0
source

Source: https://habr.com/ru/post/1524103/


All Articles