Search code examples
javaswingjlistvaluechangelistener

Getting event source instead of writing it


Firstly : I am sorry for the question name, I could not find a good name for it .

I have the following listener

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

what I want to say : Is there a method that can determine the source of the event and take its value ?

it will really help it there was 15 lists for example !

or must I write a 15 condition ?


Solution

  • You're almost there. Call arg0.getSource() and cast it to a JList, and viola, you're there! Something like:

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

    Note, the aesthete in me insists on renaming that parameter to something prettier.

    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);
         }
      }
    }