I don’t really understand the difference between the following methods for an ItemEvent object, especially in the code example below:
Object getItem() from class ItemEvent, Java-API:
Returns the item affected by the event.
ItemSelectable getItemSelectable() from class ItemEvent, Java-API:
Returns the originator of the event.
Object getSource() inherited from class EventObject, Java-API:
Returns the object on which the Event initially occurred.
What I know is, that getItemSelectable() simplifies getting the object, because I do not have to cast explicitly to use methods like getText(). (So the (JCheckBox) cast in the second println command is not necessary.) And I know, that getItemSelectable() uses getSource(). But why is there another getItem()?
But the example below does not show any difference between those methods:
JCheckBox cb = new JCheckBox("text of checkbox", true);
ItemListener myListener = new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
System.out.println(((JCheckBox) e.getItem()).getText());
System.out.println(((JCheckBox) e.getSource()).getText());
System.out.println(((JCheckBox) e.getItemSelectable()).getText());
}
};
cb.addItemListener(myListener);
Output:
text of checkbox
text of checkbox
text of checkbox
So what is the exact difference and when do I use which function?
Edit: Maybe there is no difference, at least no conceptual difference (except of return type and original class)?
If you take a look at the definition of the
ItemEventconstructor :The
ItemSelectable sourceparameter is the element that will be returned bye.getSource(). TheObject itemparameter is the element that will be returned bye.getItem().So actually the question is when the constructor is called with different object for
sourceanditem?Looking at the
JCheckBoxsuper classes –JToggleButtonandAbstractButton, the ItemEvent is always constructed with the same object for both parameter. So maybe in some custom implementation the use of these differents methods make sense.