How to add selection listener in Java?
In Java, you can add a selection listener by following these steps:
- Create a selection listener class that implements the java.awt.event.ItemListener interface and overrides its itemStateChanged method.
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class MyItemListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
// 处理选择事件的逻辑
}
}
- Add a listener to a component that requires one, such as a checkbox (JCheckBox).
JCheckBox checkBox = new JCheckBox("Check me");
checkBox.addItemListener(new MyItemListener());
In this way, when the user clicks on the checkbox, it will trigger the itemStateChanged method in MyItemListener, thereby executing the corresponding logic.