java - Swing JComboBox在选择新项目时获取上一个项目
问题描述
我是摇摆的初学者,我有以下代码:
String[] names = new String[]{
"James", "Joshua", "Matt", "John", "Paul" };
JComboBox comboBox = new JComboBox<String>(names);
// Create an ActionListener for the JComboBox component.
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// Get the source of the component, which is our combo
// box.
JComboBox comboBox = (JComboBox) event.getSource();
// Print the selected items and the action command.
Object selected = comboBox.getSelectedItem();
System.out.println("Selected Item = " + selected);
}
});
假设选择的对象是 Paul,我在 John 之后选择。所以这里 actionPerfomed 被触发并且comboBox.getSelectedItem();
会返回我们John
。我的问题是之前有什么方法可以拦截Paul
吗?
解决方案
使用addItemListener
检查是否已选择任何项目
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
String selected = (String) event.getItem();
// add your logic
}
}
});
推荐阅读
- ios - 如何在请求中使用自定义 json 数据创建多部分请求?
- javascript - 动态创建的按钮如何定位单个元素
- java - 删除(或使透明)由路径包围的画布区域
- python - 使用 Python 和 Seaborn/Pandas 绘制多个变量的图形
- c++ - C++ 新手,不知道为什么我的程序无法识别这些函数
- python - 为什么我不能让这段代码运行我不断收到类型错误:'Method' object is not subscriptable
- tensorflow - 如何避免与 keras 过拟合?
- javascript - 替代 chrome 原生消息传递
- go - Gorm 将一对多关系返回到具有嵌入式映射的结构中
- apache-zookeeper - 如何删除空闲的 Zookeeper 连接