ChangeListener

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:

sliderV.setPreferredSize( new Dimension( 50, 300) ); 

ChangeListener

Bouncing Change

As the user drags the knob across a slider change events are generated. The frequency of events depends on how fast the user drags the knob. A slow drag across the control results in an event generated for every new integer position of the knob. An event listener must potentially deal with many events everytime the user adjusts the slider.

A listener for a slider implements the ChangeListener interface. This interfaces has a single method:

public void stateChanged(ChangeEvent evt)

An object that implements the interface must be registered with the slider in order to receive events:

slider.addChangeListener( ChangeListener lstn )

Often, especially in small projects, the frame that contains the slider is also its listener.

QUESTION 8:

Say that you have a frame class that contains a slider and implements ChangeListener. Register an object of that class with its slider:

sliderV = new JSlider( JSlider.VERTICAL,  0, 1000, 400);
sliderV.setMajorTickSpacing( 100 );
sliderV.setMinorTickSpacing(  50 );
sliderV.setPaintTicks ( true );
sliderV.setPaintLabels( true ); 

sliderV.addChangeListener(  ); 

Hint: this is the same as we have been doing with frames that implement ActionListener and their buttons.