The Object getSource() Method

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

sliderA = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
sliderB = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
 . . . 
sliderA.setName( "sliderA" ); 
sliderB.setName( "sliderB" ); 

sliderA.addChangeListener( this ); 
sliderB.addChangeListener( this ); 

Any two unique strings will work. It is OK to use the same word for the reference variable and the name of a component. The two are completely separate, and Java will not get confused.

The Object getSource() Method

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 you typically use a type cast with it:

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

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

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

QUESTION 10:

(Review:) What interface does a slider's listener implement?