javaswingeventsevent-handlingjlist

Java Swing How to detect a list selection event


I'm making a simple GUI where the user can select an item from a list of Strings using the JList<String> component, and I want my program to update a JTextField with some data describing the selected item. I know I need an event listener, but I'm confused as to what I should use to detect a change in selection in my list.


Solution

  • You need to add it to the JList object:

    myJList.addListSelectionListener(new ListSelectionListener() {
    
        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println("Hello you selected me!  "
                + dataList.getSelectedValue().toString());
        }
    });