【问题标题】:setSelectedItem in JComboBox by firing event通过触发事件在 JComboBox 中设置选定项
【发布时间】:2014-07-14 15:46:22
【问题描述】:

我有一个JComboBox

JComboBox tableChoose = new JComboBox();
tableChoose.addItem("Bill");
tableChoose.addItem("Bob");
tableChoose.setSelectedItem("Bill");

以及一些处理方法

public void addComboActionListener(IComboHandler handler){
    tableChoose.addActionListener(handler);
}

public Object getTableChooseSelectedItem(){
    return tableChoose.getSelectedItem();
}

public void actionPerformed(ActionEvent event) {
    JOptionPane.showMessageDialog(null, fileReaderWindow.getTableChooseSelectedItem() , null, JOptionPane.ERROR_MESSAGE);
}

如您所见,我将“Bill”设置为第一个选项。当我运行程序时,我必须重新选择“Bill”才能触发actionPerfomed中的事件。

有没有办法在不重新选择 JComboBox 中的项目的情况下触发事件?提前谢谢你。

【问题讨论】:

  • 在设置选中项之前有没有尝试添加监听器?
  • 可能是fireActionEvent
  • @gtgaxiola 这是protected,除非你让你的类扩展JComboBox(这不是OP的场景),否则你不能调用它。
  • Mark Peters 答案是您尝试做的最佳方法

标签: java swing jcombobox


【解决方案1】:

设置选中项之前添加动作监听器:

JComboBox<String> b = new JComboBox<String>();

b.addItem("A");
b.addItem("B");
b.addItem("C");

b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JComboBox<String> src = (JComboBox<String>) e.getSource();
        System.out.println("ActionListener called. '"+src.getSelectedItem()+"' selected.");
    }
});

b.setSelectedItem("A");

输出:

ActionListener called. 'A' selected.

【讨论】:

    【解决方案2】:

    使用actionPerformed() 方法传递一个虚拟ActionEvent。例如:

    tableChoose.actionPerformed(new ActionEvent(tableChoose, 0, ""));
    

    参数应该被忽略,fireActionEvent()方法应该被触发。

    警告此建议是针对JComboBox 的源代码设计的。 cmets 声明不直接调用此方法,因此您将自行承担风险,因为将来实现可能会发生变化。

    进一步查看源代码,除了调用setSelectedItem() 方法外,没有显示任何其他触发通知的方法。

    【讨论】:

    • 这是一种protected 方法,只有当您的类与包含该方法的类在同一个包中时才能使用它。因此,如果不扩展 JComboBox,OP 将无法调用它。
    • 感谢@BackSlash,我修改了答案,改变了建议的方法
    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多