Advertisement



< Prev
Next >



ItemEvent and ItemListener




An event of type ItemEvent is generated when a source such as a checkbox is clicked to check/uncheck it or when a list item is clicked. A class to listen and respond to an event of type, ItemEvent, must implement an interface, ItemListener.




Some methods of ItemEvent class


Method Description
public Object getItem()
Returns the item which was clicked and triggered the ItemEvent.

public ItemSelectable getItemSelectable()
Returns the item which was clicked.

public int getStateChange()
Returns the current state of item which was clicked.






A class to listen and respond to ItemEvent must perform the next two steps -





Advertisement




Handling an ItemEvent by implementing ItemListener interface


In the upcoming code, we are going to create a class that will listen to an event of type, ItemEvent, by implementing the ItemListener interface. In this code, ItemEvent is generated when a source, i.e. checkbox, is clicked to check/uncheck it.

//Java - Example of ItemEvent and ItemListener

import java.awt.*;
import java.awt.event.*;


public class ItemEx1 implements ItemListener
{
Frame jf;
Checkbox chk1, chk2;
Label label1;


ItemEx1()
{
	jf= new Frame("Checkbox");
	chk1 = new Checkbox("Happy");
	chk2 = new Checkbox("Sad");
	label1 = new Label();

	jf.add(chk1);
	jf.add(chk2);

	chk1.addItemListener(this);
	chk2.addItemListener(this);

	jf.setLayout(new FlowLayout());	
	jf.setSize(220,150);
	jf.setVisible(true);
}

public void itemStateChanged(ItemEvent ie)
{
	Checkbox ch =(Checkbox)ie.getItemSelectable();
	if(ch.getState()==true)
	{
		label1.setText(ch.getLabel()+ " is checked");
		jf.add(label1);
		jf.setVisible(true);
	}
	else
	{
		label1.setText(ch.getLabel()+ " is unchecked");
		jf.add(label1);
		jf.setVisible(true);
	}
}

public static void main(String... ar)
{
	new ItemEx1();
}

}

When you run the code, you are presented a window shown in the Figure2 below -:

Figure 1


When you check a checkbox an event ItemEvent is fired and you are presented a message to display which checkbox is last checked/unchecked. For example, when you check the checkbox with label- happy, you are notified like -

Figure 2


When you uncheck this checkbox, an event ItemEvent is fired you are notified with a message that you've unchecked the checkbox(including its name).

Figure 3




Please share this article -





< Prev
Next >
< MouseMotionListener
WindowListener



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement