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?