【问题标题】:Getting event source instead of writing it获取事件源而不是编写它
【发布时间】:2013-11-29 17:08:21
【问题描述】:

首先:我很抱歉这个问题的名字,我找不到一个好名字。

我有以下监听器

public void valueChanged(ListSelectionEvent arg0) {
        if(!(arg0.getValueIsAdjusting())){
            result.setText(result.getText()+arg0.getSource().getSelectedValue().toString());//I know it is wrong!
        }
}

我想说的是:有没有一种方法可以确定事件的来源并取其值?

例如,如果有 15 个列表,它真的会有所帮助!

还是我必须写一个 15 条件?

【问题讨论】:

    标签: java swing jlist valuechangelistener


    【解决方案1】:

    你快到了。调用 arg0.getSource() 并将其转换为 JList,中提琴,你就在那里!类似的东西:

    String selection = ((JList) arg0.getSource()).getSelectedValue().toString();
    result.setText(result.getText() + selection);
    

    请注意,我的美学家坚持将那个参数重命名为更漂亮的东西。

    public void valueChanged(ListSelectionEvent lsEvent) {
      if(!(lsEvent.getValueIsAdjusting())){
         JList list = (JList) lsEvent.getSource();
         Object selection = list.getSelectedValue(); // if not using generics
         if (selection != null) {
            String stringSelection = selection.toString();
            result.setText(result.getText() + stringSelection);
         }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多