Home » Desktop Java » awt » event » ChangeListener example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

ChangeListener example

In this example we are going to see how to use the ChangeListener interface in Java. This is very useful when you want to monitor generic changes in your application.

In short, to use a simple ChangeListener one should follow these steps:

  • Create a new ChangeListener instance.
  • Override the stateChanged method to customize the handling of specific events.
  • Use specific functions of components to get better undemanding of the event that occurred.

 
Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import javax.swing.DefaultBoundedRangeModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {

    public Main() {

  try {

DefaultBoundedRangeModel mdl = new DefaultBoundedRangeModel();

ChangeListener changeListener = new MyChangeListener();

mdl.addChangeListener(changeListener);

System.out.println(mdl.toString());

System.out.println("Min = 120");

mdl.setMinimum(120);

System.out.println(mdl.toString());

System.out.println("MAn = 90 . . .");

mdl.setMaximum(90);

System.out.println(mdl.toString());

System.out.println("Max = 80 . . .");

mdl.setMaximum(80);

System.out.println(mdl.toString());

System.out.println("Extent to 50 . . .");

mdl.setExtent(50);

System.out.println(mdl.toString());

System.out.println("Change random properties ");

if (!mdl.getValueIsAdjusting()) {

    mdl.setValueIsAdjusting(true);

    System.out.println(mdl.toString());

    mdl.setMinimum(0);

    mdl.setMaximum(100);

    mdl.setExtent(20);

    mdl.setValueIsAdjusting(false);

}

System.out.println(mdl.toString());

  } catch (Exception ex) {

ex.printStackTrace();

  }
    }

    class MyChangeListener implements ChangeListener {

  @Override

  public void stateChanged(ChangeEvent event) {

System.out.println("A ChangeEvent has occured");

  }
    }

    public static void main(String args[]) {

  new Main();
    }
}

 
This was an example on how to use ChangeListener in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of