【发布时间】:2020-05-18 02:11:12
【问题描述】:
我是挥杆初学者 我有以下代码:
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 吗?
【问题讨论】:
-
好吧,你可以使用
ItemListener,它会根据记忆告诉你“from”和“to”事件,或者你可以只保留对最后选择的值的引用:/ -
我该如何实现它?
-
嗯,你可以从How to Write an Item Listener 开始,我认为How to Use Combo Boxes 有一些例子