In the following code, I have two different JLists, and I'm trying to code them to where if I have an object selected in one list and then click on an object in the other list, the object that was selected in the previous list will be deselected while the object in the other list will be selected at the same time. I think it will be obvious as to what I'm trying to do if you take a look at the code (the code is simple).
package list; import javax.swing.SwingUtilities; public class ListMain { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new CreateLists(); } }); } } package list; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.WindowConstants; public class CreateLists extends JFrame { private JList<String> leftList, rightList; private DefaultListModel<String> leftListModel, rightListModel; private ListListener listener; public CreateLists() { initComponents(); setVisible(true); } private void initComponents() { leftList = new JList<String>(); rightList = new JList<String>(); leftListModel = new DefaultListModel<String>(); rightListModel = new DefaultListModel<String>(); listener = new ListListener(leftList, rightList); setSize(350, 250); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); leftList.setPreferredSize(new Dimension(100, 75)); rightList.setPreferredSize(new Dimension(100, 75)); leftList.setModel(leftListModel); rightList.setModel(rightListModel); leftList.addListSelectionListener(listener); rightList.addListSelectionListener(listener); leftListModel.addElement("First"); leftListModel.addElement("Second"); rightListModel.addElement("Third"); rightListModel.addElement("Fourth"); add(leftList, BorderLayout.WEST); add(rightList, BorderLayout.EAST); } } package list; import javax.swing.JList; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListListener implements ListSelectionListener { private JList<String> leftList, rightList; public ListListener(JList<String> leftListRef, JList<String> rightListRef) { leftList = leftListRef; rightList = rightListRef; } @Override public void valueChanged(ListSelectionEvent event) { if (event.getSource().equals(leftList)) { rightList.clearSelection(); } if (event.getSource().equals(rightList)) { leftList.clearSelection(); } } }
With the code above, you have to "double-click" the item in the other list to select the new item. I need it to immediately deselect the old item and select the new item in the other list at the same time. I haven't been able to get this to work yet. Any ideas?