You must give your class your own name (not Class1 ) so that your intent becomes clear. Maybe you want to have a counter ?:
package so3274211; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Counter { private int value = 0; private final List<Listener> listeners = new CopyOnWriteArrayList<Listener>(); private void fireAfterValueChanged() { for (Listener listener : listeners) { listener.afterValueChanged(this); } } public int getValue() { return value; } public void increment() { value++; fireAfterValueChanged(); } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public interface Listener { void afterValueChanged(Counter counter); } }
In regular Java code, you cannot directly listen to a variable. But if you insert this variable into a simple object with the appropriate modification methods ( increase() in this case), you can call listeners from this method.
To call a listener, you need to register it somehow. This is usually done using a simple List<Listener> , and the interface to it consists of two methods addListener(Listener) and removeListener(Listener) . This pattern can be found throughout AWT and Swing.
I defined the Listener interface inside the Counter class, because this interface does not really matter outside this class, and I did not want to call it CounterListener . Thus, the number of .java files is less.
Using this counter in a real program might look like this:
package so3274211; public class Main { public static void main(String[] args) { Counter c = new Counter(); c.increment(); c.addListener(new Counter.Listener() { @Override public void afterValueChanged(Counter counter) { System.out.println(counter.getValue()); } }); c.increment(); } }
First I created a counter, and then added a listener to it. The expression new Counter.Listener() { ... } is an anonymous class definition that also often appears in Java GUI programming.
So, if you are serious about programming using the graphical interface, you need to learn these concepts and implementation methods (encapsulating a variable in a class, adding a listener code, defining a listener, calling a listener from code that changes the variable) anyway.