I am not sure why everything is printing twice. For example, if you press "Male", then the program will print MaleMale. This is a part of a bigger program: I want gender (a String) to store the last selection. Is this code doing that?
DefaultListModel toAdd = new DefaultListModel();
toAdd.addElement("Male");
toAdd.addElement("Female");
toAdd.addElement("Others");
JList list = new JList();
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(new TitledBorder(null, "How do you identify yourself?", `
TitledBorder.CENTER, TitledBorder.TOP, null, null));
list.setBackground(SystemColor.info);
list.setBounds(57, 85, 244, 97);
list.setModel(toAdd);
frame.getContentPane().add(list);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged (ListSelectionEvent event) {
int lastSelIx = list.getMaxSelectionIndex();
gender = (String) list.getModel().getElementAt(lastSelIx);
System.out.print(gender);
}
);
}