Reputation: 533
I add a listener to JCheckBox component and I want call listener manually.how do it?
myCheckBox.selected(false)
then I want to called myCheckBox listener. Do you have better idea?
Upvotes: 3
Views: 3349
Reputation: 417
Instead of trying to call the Listener, why not just use a separate method?
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
method();
}
};
public void method() {
//code you want to run
}
Then just call method()
when you want to run the code separate from the Listener.
Upvotes: 0
Reputation: 707
I know I'm a bit late, but this should do the trick:
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
//whatever your itemStateChanged() looks like.
}
};
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(listener);
Then, whenever you need to call it manually:
listener.itemStateChanged(
new ItemEvent(checkBox, ItemEvent.ITEM_STATE_CHANGED, checkBox, 0));
If you created your listener anonymously, you can still access it like:
checkBox.getItemListeners()[0].itemStateChanged(
new ItemEvent(checkBox, ItemEvent.ITEM_STATE_CHANGED, checkBox, 0));
Upvotes: 6
Reputation: 1099
I really don't know what checkBox component you use. You don't tell us which framework do you use or provide other helpful context infos.
But in general: Your listener is impl. an interface. This interface defines the callbackmethod that your component (checkBox) calls.
If you have a instance of your listener obj. you can call this method directly.
Upvotes: 0