event
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.