go to previous page   go to home page   go to next page

Answer:

if ( source.getName()().equals("sliderA") )
  textA.setText( source.getValue() + " " );
if ( source.getName()().equals("sliderB") )
  textB.setText( source.getValue() + " " );

Complete Program

Sliders and Change Listener

Here is the complete (but useless) application. Some points of interest are colored blue. To use change events, import javax.swing.event.*. Study how (1) the sliders, (2) the change events they generate, and (3) the listener method cooperated to send the correct values in the text fields.

Each slider has the same preferred size, set with setPreferredSize(). A better-engineered program would use the same Dimension object for each call, and would use final ints rather than integer literals. The layout management depends on the size of the frame and the size of the components. Grouping the components into panels would be better.

import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.* ;

public class SliderFive extends JFrame implements ChangeListener
{
  JSlider    sliderA, sliderB;
  JTextField textA,   textB;
  
  public SliderFive()  
  { 
    setTitle( "Change Listener" );
    setDefaultCloseOperation( EXIT_ON_CLOSE );
    
    sliderA = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
    sliderA.setMajorTickSpacing( 100 );
    sliderA.setMinorTickSpacing(  50 );
    sliderA.setPaintTicks( true );
    sliderA.setPaintLabels( true );
    sliderA.setPreferredSize( new Dimension(300,50) ) ;
    sliderA.addChangeListener( this );
    sliderA.setName("sliderA"); 
    textA   = new JTextField( 4 );
    textA.setText( sliderA.getValue() + " " );
    
    sliderB = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
    sliderB.setMajorTickSpacing( 100 );
    sliderB.setMinorTickSpacing(  50);
    sliderB.setPaintTicks( true );
    sliderB.setPaintLabels( true );
    sliderB.setPreferredSize( new Dimension(300,50) ) ;
    sliderB.addChangeListener( this ); 
    sliderB.setName("sliderB"); 
    textB   = new JTextField( 4 );
    textB.setText( sliderB.getValue() + " " );
   
    // frame
    setLayout( new FlowLayout() );
    add( textA  );
    add( sliderA  );
    add( textB  );
    add( sliderB  );
  }
   
  public void stateChanged( ChangeEvent evt )
  {
    JSlider source;
    source = (JSlider)evt.getSource();
    
    if ( source.getName().equals("sliderA") )
      textA.setText( source.getValue() + " " );
      
    if ( source.getName().equals("sliderB") )
      textB.setText( source.getValue() + " " );
  }
  
  public static void main ( String[] args )
  {
    SliderFive theApp  = new SliderFive() ;
    theApp.setSize( 400, 150 );  
    theApp.setResizable( false ); 
    theApp.setVisible( true );        
  }
}

QUESTION 12:

(Review: ) How many change events are generated when the user moves the slider knob from one value to another?