Detecting a change in an integer - java

Is there any way to detect change in an integer? Such as creating a listener to listen to the integer to detect and change in value it has. I know this is possible with booleans with a few tricks but I cannot seem to adapt this to an int value. Does anyone have any idea how this could be done? I need to know how to do this in the Java language. Below is code that I found online that allows for a boolean listener. How can I convert this to an integer listener?
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
//can u see this austin? can u see this i typed this at 9:33 my time
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class test1 implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() { // add this to the class
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
test1 test = new test1(false);
test.addBooleanChangeListener(listener);
// test.setFlag(false); // no change, no event dispatch
// test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public test1(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}

I would create a class capable of registering listeners. Below is a mocked up example. It might even compile as is (assuming you write the corresponding VocalIntegerListener interface exists and is implemented somehow... it's pretty simple).
class VocalInteger {
private int value;
private final Object lock = new Object();
Set<VocalIntegerListener> listeners; // assume interface exists - it's easy
public VocalInteger() {
this(0);
}
public VocalInteger(int value) {
this.value = value;
listeners = new HashSet<VocalIntegerListener>();
}
public int getValue() {
return value;
}
public void setValue(int value) {
synchronized(lock) {
int oldValue = this.value;
this.value = value;
for(VocalIntegerListener listener : listeners) {
listener.fireChangedEvent(oldvalue, value); // assume exists
}
}
}
public void registerListener(VocalIntegerListener listener) {
synchronized(lock) {
listeners.add(listener);
}
}
}

Have a look at "Java Beans" and "bound properties" for the standard approach how to listen for property changed events:
http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html
http://docs.oracle.com/javase/tutorial/javabeans/

Related

How to fire events using Bukkit API?

I was looking at how to create and fire events using Bukkit API.
public class PlayerDisconnect implements Listener {
#EventHandler
public void onQuit(PlayerQuitEvent event){
//code
}
}
I mean, doesn't matter the name of the method (in this case onQuit, I can use onDisconnect, onLeave, etc. and it will still be called by PlayerQuitEvent), it calls every method using PlayerQuitEvent as a parameter. I want to be able to replicate that behaviour.
You can create and call your own custom events using the Bukkit Event API. Spigot has a good starting tutorial on the Event API.
A simple example of a Cancellable event that takes a Player:
...
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class MyCustomEvent extends Event implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
private final Player player;
private boolean cancelled;
public MyCustomEvent(Player player)
{
this.player = player;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public Player getPlayer()
{
return this.player;
}
public HandlerList getHandlers()
{
return handlers;
}
#Override
public boolean isCancelled()
{
return cancelled;
}
#Override
public void setCancelled(boolean cancelled)
{
this.cancelled = cancelled;
}
}
Which you can then call elsewhere in your custom event like so
...
MyCustomEvent event = new MyCustomEvent(player);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
return;
...
Finally, you would listen for the event like you would any other event:
...
#EventHandler
public void onMyCustomEvent(MyCustomEvent event){
Player player = event.getPlayer();
...
}
You should use PluginManager#callEvent(Event).
public class CustomEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final String a;
private final int b;
private boolean cancelled;
public CustomEvent(String a, int b) {
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public int getB() {
return b;
}
#Override
public boolean isCancelled() {
return cancelled;
}
#Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
#Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
CustomEvent event = new CustomEvent("some data", 5);
Server server = ...
server.getPluginManager().callEvent(event);
if (event.isCancelled()) return;
// Do event
See the official tutorial and this community tutorial.
If you want to use the Bukkit event system in a non-Bukkit plugin project, you can add the Bukkit API as dependency (just the API, not the server implementing it).

How to make a complex object an Observable

I have multiple JavaFX panes and canvases that reference a complex object with data they need, and I want them to redraw when the object changes.
This would call for the object to be Observable, but which class do I use? JavaFX seems to mostly have ObservableValue subclasses, which wrap a value and allow swapping it out. I don't want to swap out the complex object, just notify the listeners when changes occur. I could do that by implementing addListener, but I'm sure there's a subclass that does it for me already.
class ComplexObject /* extends SomeObservableClass */ {
public int getValue1 { complex calculations... };
public int getValue2 { ... };
public void setNewValue1(int newValue) { ... }
}
class ComplexRenderer extends Canvas implements InvalidationListener {
private ComplexObject complexObject;
public void setComplexObject(ComplexObject complexObject) {
this.complexObject = complexObject;
complexObject.addListener(this);
}
public void draw() { ... }
}
Which class should ComplexObject extend? Is there something that maintains the list of listeners and has something like fireValueChangedEvent() so I can make it notify all listeners?
Everything I see in JavaFX seems to be geared towards properties, which don't seem the right choice here.
Not really sure what you meant by swapping, and not really sure if I understood you right.
class ComplexObject {
private IntegerProperty value1 = new SimpleIntegerProperty();
private IntegerProperty value2 = new SimpleIntegerProperty();
private BooleanProperty internalChanged = new SimpleBooleanProperty(false);
public ComplexObject() {
this.internalChanged.bind(Bindings.createBooleanBinding(() ->
this.internalChanged.set(!this.internalChanged.get()), this.value1, this.value2));
}
public IntegerProperty value1Property() { return this.value1; }
public int getValue1() { return this.value1.get(); }
public void setValue1(int value) { return this.value1.set(value); }
public IntegerProperty value2Property() { return this.value2; }
public int getValue2() { return this.value2.get(); }
public void setValue2(int value) { return this.value2.set(value); }
public void setNewValue1(int newValue) { /* What value is this??? */ }
public BooleanProperty internalChangedProperty() { return this.internalChanged; }
}
class ComplexRenderer extends Canvas implements InvalidationListener {
private ComplexObject complexObject;
public void setComplexObject(ComplexObject complexObject) {
this.complexObject = complexObject;
complexObject.internalChangedProperty().addListener(this);
}
#Override public void invalidated(Observable observable) {
// Something inside complex object changed
}
public void draw() { ... }
}
Maybe you can have a look at the Interface ObjectPropertyBase<T> and the classes ObjectPropertyBase<T> and SimpleObjectProperty<T> which implements Observable.
However you have to define when your object changes and listening logic.
I'm sorry it's just a trace of work, but I hope it may be useful.

Return a value after thread finish its work

I tried to implement Observer pattern in java with threads. What I am trying to do is return a value from the new thread.
In this question, someone recommend to use Observer pattern and I want to use it.
I have the following code:
/*Observable*/
public class QRExplorer extends Observable implements Runnable {
private String md5;
public String getMD5()
{
return md5;
}
private void setMD5(String value)
{
this.md5 = value;
setChanged();
notifyObservers();
}
#Override
public void run() {
// do some stuff
// here I should obtain a string and I want return that
setMD5("value");
}
}
/*Observer*/
public class Observador implements Observer {
private QRExplorer observado = null;
public Observador(QRExplorer observado)
{
this.observado = observado;
}
#Override
public void update(Observable o, Object arg) {
if(o == observado)
{
System.out.println("Something has changed ¬¬: "+observado.getMD5());
}
}
}
/*Principal class*/
public class MainView extends javax.swing.JFrame implements ThreadFactory{
private RKeyListener listener;
private Webcam camara;
private Executor creador = Executors.newSingleThreadExecutor(this);
private Observador observador;
private QRExplorer explorer;
/*Nothing relevant*/
private void pCamaraMouseClicked(java.awt.event.MouseEvent evt) {
creador.execute(explorer);
}
#Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
Observable obs = (Observable)t;// but Netbeans tells me: incompatible types: Thead cannot be converted to Observable
obs.addObserver(observador);
return t;
}
}
Try
#Override
public Thread newThread(Runnable r) {
explorer = new QRExplorer(); // extends Observable
observador = new Observador(explorer); //implements Observer
explorer.addObserver(observador);
Thread t = new Thread(r);
return t;
}

Can I check if a void method returned?

I just want to ask, if it is possible to check if a void method "cancelled" itself by calling return;?
For example in my main I call calculate(myArray);, which is defined as follows:
public static void calculate(Object[] array) {
if (array == null)
return;
// do stuff
}
Is their a way to know, if it returned or not? My thoughts were making a "global" boolean which is changed to true right before we return and then check its value in main or just change the return type to something like int and when it returned at the beginning we use return -1; and at the end of the method return 0;
Both is possible but I think neither of them is very good style. Is there an alternative?
You are right that the practices you described are considered bad in Java (and other modern languages).
The most common acceptable practices for your scenario are:
Make the method throw an exception. Do this if the "failing" code path shouldn't happen under normal circumstances.
Make the method's return type bool to indicate success or failure. Do this if the "failing" code path can happen under normal circumstances as well.
No, you cannot. From The Oracle Java tutorials - Returning a Value from a Method:
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
There is no way from method invocation to determine if the void method was completed by a fall-through block or a return; statement.
Most other methods includes a return type of boolean and returns false when something went wrong, or simply throws an IllegalArgumentException.
You can utilize publisher - listener pattern :)
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
public class Sample {
private interface Event {
}
private static class ExitEvent implements Event {
}
private static class SucceedEvent implements Event {
}
private interface EventListener {
void eventPerformed(Event e);
}
private static List<EventListener> listeners = new LinkedList<EventListener>();
private static void addActionListener(EventListener l) {
listeners.add(l);
}
private static void fireEvent(Event event) {
for (EventListener l : listeners) {
l.eventPerformed(event);
}
}
public static void calculate(Object[] array) {
if (array == null) {
fireEvent(new ExitEvent());
return;
}
fireEvent(new SucceedEvent());
}
public static void main(String[] args) {
addActionListener(new EventListener() {
public void eventPerformed(Event e) {
if (e instanceof ExitEvent) {
System.out.println("Exit");
} else if (e instanceof SucceedEvent) {
System.out.println("Success");
}
}
});
calculate(null);
calculate(new Object[] {});
}
}
Output:
Exit
Success
You can go much farther and remove those ugly ifs, by utilizing visitor pattern
import java.util.LinkedList;
import java.util.List;
public class Sample {
private interface EventVisitor {
void visit(ExitEvent event);
void visit(SucceedEvent event);
}
private interface Event {
void accept(EventVisitor visitor);
}
private static class ExitEvent implements Event {
public void accept(EventVisitor visitor) {
visitor.visit(this);
}
}
private static class SucceedEvent implements Event {
public void accept(EventVisitor visitor) {
visitor.visit(this);
}
}
private interface EventListener {
void eventPerformed(Event e);
}
private static List<EventListener> listeners = new LinkedList<EventListener>();
private static void addActionListener(EventListener l) {
listeners.add(l);
}
private static void fireEvent(Event event) {
for (EventListener l : listeners) {
l.eventPerformed(event);
}
}
public static void calculate(Object[] array) {
if (array == null) {
fireEvent(new ExitEvent());
return;
}
fireEvent(new SucceedEvent());
}
public static void main(String[] args) {
addActionListener(new EventListener() {
public void eventPerformed(Event e) {
e.accept(new EventVisitor() {
public void visit(SucceedEvent event) {
System.out.println("Success");
}
public void visit(ExitEvent event) {
System.out.println("Exit");
}
});
}
});
calculate(null);
calculate(new Object[] {});
}
}
Output:
Exit
Success

Java Event Listener to detect a variable change

I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it possible to create a custom event listener to detect this?
Please I cannot seem to find a solution to this anywhere and I found this website explaining how to create custom events
Use PropertyChangeSupport. You wont have to implement as much and it is thread safe.
public class MyClassWithText {
protected PropertyChangeSupport propertyChangeSupport;
private String text;
public MyClassWithText () {
propertyChangeSupport = new PropertyChangeSupport(this);
}
public void setText(String text) {
String oldText = this.text;
this.text = text;
propertyChangeSupport.firePropertyChange("MyTextProperty",oldText, text);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class MyTextListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("MyTextProperty")) {
System.out.println(event.getNewValue().toString());
}
}
}
public class MyTextTest {
public static void main(String[] args) {
MyClassWithText interestingText = new MyClassWithText();
MyTextListener listener = new MyTextListener();
interestingText.addPropertyChangeListener(listener);
interestingText.setText("FRIST!");
interestingText.setText("it's more like when you take a car, and you...");
}
}
Just like you need to create an event listener, you will also need to create the event firer -- since there is nothing automatic that will do this for you. I've provided sample code that shows you how to implement such a firer.
This test implementation isn't perfect. It only includes a way to add listeners. You may wish to include a way to remove listeners who are no longer interested in receiving events. Also note that this class is not thread-safe.
import java.util.List;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.awt.EventQueue;
/**
* This class uses the EventQueue to process its events, but you should only
* really do this if the changes you make have an impact on part of a GUI
* eg. adding a button to a JFrame.
*
* Otherwise, you should create your own event dispatch thread that can handle
* change events
*/
public class BooleanChangeTest implements BooleanChangeDispatcher {
public static void main(String[] args) {
BooleanChangeListener listener = new BooleanChangeListener() {
#Override
public void stateChanged(BooleanChangeEvent event) {
System.out.println("Detected change to: "
+ event.getDispatcher().getFlag()
+ " -- event: " + event);
}
};
BooleanChangeTest test = new BooleanChangeTest(false);
test.addBooleanChangeListener(listener);
test.setFlag(false); // no change, no event dispatch
test.setFlag(true); // changed to true -- event dispatched
}
private boolean flag;
private List<BooleanChangeListener> listeners;
public BooleanChangeTest(boolean initialFlagState) {
flag = initialFlagState;
listeners = new ArrayList<BooleanChangeListener>();
}
#Override
public void addBooleanChangeListener(BooleanChangeListener listener) {
listeners.add(listener);
}
#Override
public void setFlag(boolean flag) {
if (this.flag != flag) {
this.flag = flag;
dispatchEvent();
}
}
#Override
public boolean getFlag() {
return flag;
}
private void dispatchEvent() {
final BooleanChangeEvent event = new BooleanChangeEvent(this);
for (BooleanChangeListener l : listeners) {
dispatchRunnableOnEventQueue(l, event);
}
}
private void dispatchRunnableOnEventQueue(
final BooleanChangeListener listener,
final BooleanChangeEvent event) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
listener.stateChanged(event);
}
});
}
}
interface BooleanChangeDispatcher {
public void addBooleanChangeListener(BooleanChangeListener listener);
public boolean getFlag();
public void setFlag(boolean flag);
}
/**
* Listener interface for classes interested in knowing about a boolean
* flag change.
*/
interface BooleanChangeListener extends EventListener {
public void stateChanged(BooleanChangeEvent event);
}
/**
* This class lets the listener know when the change occured and what
* object was changed.
*/
class BooleanChangeEvent extends EventObject {
private final BooleanChangeDispatcher dispatcher;
public BooleanChangeEvent(BooleanChangeDispatcher dispatcher) {
super(dispatcher);
this.dispatcher = dispatcher;
}
// type safe way to get source (as opposed to getSource of EventObject
public BooleanChangeDispatcher getDispatcher() {
return dispatcher;
}
}
you can also try to implement an Observer.
First create the observable object:
import java.util.Observable;
public class StringObservable extends Observable {
private String name;
public StringObservable(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
}
Then the observer:
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
}
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
name = (String) arg;
System.out.println("NameObserver: Name changed to " + name);
} else {
System.out.println("NameObserver: Some other change to subject!");
}
}
}
And in your main (or wherever else):
public class TestObservers {
public static void main(String args[]) {
// Create the Subject and Observers.
StringObservable s = new StringObservable("Test");
NameObserver nameObs = new NameObserver();
// Add the Observer
s.addObserver(nameObs);
// Make changes to the Subject.
s.setName("Test1");
s.setName("Test2");
}
}
Mostly found here
Very late to answer, but this is a problem that can be solved with Observer/Observable. Example
The boolean you are setting should be allowed to do only through a setter method like:
public void setFlag(boolean flag){
//Method code goes here
}
Now in now set method, you can decide based on what value comes in, what event needs to be fired. I am explaining in simple terms without introducing complex terms so you can understand better, so code snippet would look like:
public void setFlag(boolean flag){
//if flag is TRUE do something
//If flag is FALSE then do something
//And finally do what you needed to do with flag
}
Ask questions if you need more info
you create a listener when you want to listen for I/O changes. mostly on graphics.
the answer to your question is to keep state of the running program, then check if variables change from the state inside the infinite loop of your program.
You can use AOP for that, perhaps AspectJ? Check a few examples here (if you use Eclipse, then using AspectJ is really simple with their plugin).
For you, you would have a pointcut similar to the one used in the SampleAspect, but one that will only be used when someone makes a new SET to a boolean variable (this doesn't mean that the value has changed, just that someone loaded a value to the variable).

Categories