I have a JList which is a list of names and I want to print out any item that I select from the list. It sounds simple but I do not know how to do it. Here is my code:
final DefaultListModel<String> myNamesList = new DefaultListModel<String>();
final JList list = new JList(myNamesList);
final Object chosenName = list.getSelectedValue();
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
System.out.println(chosenName);
}
});
Make sure the
Object chosenName = list.getSelectedValue();
line is within the valueChanged()
method. Otherwise it will always be the initial selected value.