I am referring to this exact problem with cyclic JComboBox updates. I was thinking, maybe instead of using flags or a mouselistener, is there a way of creating a toggleable actionlistener yourself?
I wrote this so far:
public abstract class ToggledActionListener implements java.awt.event.ActionListener {
private volatile boolean enabled;
protected ToggledActionListener(){
enabled = true;
}
public synchronized void setEnabled(boolean flag){
enabled = flag;
}
public synchronized boolean isEnabled(){
return enabled;
}
}
Now I am trying to find a way to cancel any actionPerformed() calls from objects that extend this class IF enabled is false.
Is this even possible?
CodePudding user response:
Create an abstract class ToggledActionListener with only 1 abstract method like so:
public abstract class ToggledActionListener implements java.awt.event.ActionListener {
private boolean isEnabled;
public ToggledActionListener(){
isEnabled = true;
}
public void setEnabled(boolean flag){
isEnabled = flag;
}
public boolean isEnabled(){
return isEnabled;
}
@Override
public final void actionPerformed(ActionEvent e) {
if(isEnabled){
runIfAllowed(e);
}
}
abstract void runIfAllowed(ActionEvent e);
}
You can then use it like:
someButton.addActionListener(someToggledActionListener);
or
someButton.addActionListener(new ToggledActionListener({
@Override
void runIfAllowed(ActionEvent e){
//some code
}
});
Use someToggledActionLister.setEnabled(false)
to avoid cyclic event firing.