java - getItem 和 getSelectedItem 之间的区别

标签 java swing jcombobox

在 Swing 中使用 JComboBox 并读取所有接口(interface)和类及其各种属性时,我不会对 ComboBoxEditorgetItem 之间的问题感到困惑 方法,以及 JComboBoxgetSelectedItem

我是从可编辑组合框的角度来看的。当我在组合框中编辑一些文本并按 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,然后使用modelsetSelectedItem(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/

相关文章:

java - 将 JCombobox 渲染到正确的问题

java - 我如何处理在我的 Activity 停止时发送的广播?

java - 如何在 ScrollBar 旁边放置一个 Bar

java - 如何仅在 JTable 中的特定单元格中设置 JComboBox

java - 如何处理组合框中的超长文本项

java - 如何在 JPanel 类中创建 JList "refresh"方法

java - 如何在 Java 中将图像放入 Object[] 中?

java - init 方法中的 @Nonnull 字段

java - 无法从对 servlet 的 ajax 调用中检索 session 属性

java - 在 JTabbedPane 中拆分标签