在 Swing 中使用 JComboBox
并读取所有接口(interface)和类及其各种属性时,我不会对 ComboBoxEditor
的 getItem 之间的问题感到困惑
方法,以及 JComboBox
的 getSelectedItem
。
我是从可编辑组合框的角度来看的。当我在组合框中编辑一些文本并按 Enter 键后调用这两个方法时,这两个方法都会返回相同的值。当然,这是预料之中的,但这两种方法的具体用途是什么?从组合框代码中调用它们的顺序有什么不同吗?
最佳答案
ComboBoxEditor 的 getItem()
函数返回编辑项目
JComboBox getSelectedItem()
返回选定的项目。不过,要具体说明您的问题:
Is there any difference in the order in which they are called from within the combo box's code ?
可编辑的组合框使用编辑器来显示所选项目。一旦编辑了某个项目,就会在 JComboBox
的已注册 ComboBoxEditor
实例上触发一个操作事件。编辑器 Action 监听器实现的actionPerformed
函数,从editor
获取编辑后的item
,然后使用model
的 setSelectedItem(item)
函数,从以下源代码中可以明显看出:
public void actionPerformed(ActionEvent e) {
Object newItem = getEditor().getItem(); // get edited's item
setPopupVisible(false);
getModel().setSelectedItem(newItem); // model set the item as selected
String oldCommand = getActionCommand();
setActionCommand("comboBoxEdited");
fireActionEvent();
setActionCommand(oldCommand);
}
然后,当我们请求获取 getSelectedItem()
时,它会通过询问model
来返回所选项目。
关于java - getItem 和 getSelectedItem 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467271/