You should give your class a proper name (not Class1
), so that your intention 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 ordinary Java code you cannot listen to a variable directly. But if you put that variable into a simple object with proper modification methods (increase()
in this case), you can call the listeners from this method.
To call a listener you have to somehow register it. This is usually implemented with a simple List<Listener>
, and the interface to that consists of the two methods addListener(Listener)
and removeListener(Listener)
. You can find this pattern everywhere in AWT and Swing.
I have defined the Listener
interface inside the Counter
class because this interface doesn't have much value outside that class, and I didn't want to call it CounterListener
. That way, there are fewer .java
files flying around.
Using that counter in an actual program may 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();
}
}
I first created a counter and then added a listener to it. The expression new Counter.Listener() { ... }
is an anonymous class definition, which also appears often in Java GUI programming.
So if you are serious about GUI programming you need to learn these concepts and implementation techniques (encapsulating a variable in a class, adding the listener code, defining a listener, calling the listener from the code that modifies the variable) anyway.