4

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);
    }
SorenRomer
  • 217
  • 1
  • 10
  • Check out this answer: http://stackoverflow.com/questions/9825572/how-do-i-get-from-the-event-object-the-object-on-which-there-was-this-event Hope it helps! – rodrigopdl.89 Jan 28 '14 at 15:42

5 Answers5

4

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.

Someone
  • 551
  • 3
  • 14
3

You don't cast the event itself, but you cast the nested source.

In your case you get the source via:

event.getSource();

and you cast it, obviously because it's of type that can be casted to JSlider. The getSouce() method contract says it returns an Object instance, and therefore casting at runtime it will either pass, or will fail and you will receive a ClassCastException.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

An event object contains a reference to the component that generated the event. To extract that reference from the event object use:

Object getSource()

Since the return type of getSource() is Object (the class at the very top of the class hierarchy) use a type cast with it:

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

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

Now you have a reference to the slider that caused the event and you can use any of that slider's methods.

0

The ChangeEvent contains a reference to a source object (which could be anything that throws a ChangeEvent). In this case you know that it is a JSlider, so you can cast the event-source to JSlider.

koljaTM
  • 10,064
  • 2
  • 40
  • 42
0

This is because an Event can be generated from a variety of sources (Swing Components).

Since this is the case, you need to cast to the appropriate type.

If you didn't cast to JSlider, you could not use the getValue() method.

Menelaos
  • 23,508
  • 18
  • 90
  • 155