Java ItemListener in AWT
Last Updated :
07 Nov, 2023
The Java ItemListener user interface in Java’s Abstract Window Toolkit (AWT) is a crucial component for managing user interactions with elements like checkboxes and option lists. In this article, we wish to search how the ItemListener interface is old in AWT to respond to exploiter input.
The ItemListener interface is divided into the java.awt.event package and extends the EventListener user interface. It plays a very material role in handling user actions such as selecting or deselecting items in components like checkboxes, choice lists, and checkbox groups. To utilize the ItemListener, you need to implement this interface in a class that processes the ItemEvent. The object of this class is then registered with the GUI portion that generates the ItemEvent exploitation of the addItemListener() method. When the user interacts with the part, the itemStateChanged method of the documented physical object is invoked to respond to the user’s actions.
Declaration of ItemListener
public interface ItemListener extends EventListener {
void itemStateChanged(ItemEvent e);
}
ItemListener Method
This method is invoked when an item has been selected or deselected by the user. It takes an ItemEvent object as a parameter, providing information about the event, such as the source of the event and the type of change (selected or deselected).
|
Java ItemListener Example
Java
import java.awt.*;
import java.awt.event.*;
class CheckboxExample {
public static void main(String[] args) {
Frame frame = new Frame( "Checkbox Example" );
Checkbox checkbox = new Checkbox( "Enable Feature" );
MyItemListener itemListener = new MyItemListener();
checkbox.addItemListener(itemListener);
frame.add(checkbox);
frame.setSize( 300 , 200 );
frame.setLayout( new FlowLayout());
frame.setVisible( true );
}
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println( "Feature is enabled." );
} else {
System.out.println( "Feature is disabled." );
}
}
}
|
Output:
Inside terminal the message is shown like below:
In this example, we have create a very basic GUI cover that has a “Enable Feature” checkbox. The itemStateChanged method is called in response to the user’s selection or deselection of the checkbox, and we implement the ItemListener port in the MyItemListener class.
Share your thoughts in the comments
Please Login to comment...