Re: Sharing ListSelection
To: comp.lang.java.gui
John B. Matthews wrote:
perhaps something like this might work:
A couple of things concern me about this code.
<code>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SR extends JFrame {
SR extends JFrame, but is nowhere used.
Inheritance? Composition?
private static boolean useLast = false;
nit: the second initialization to 'false' is redundant, as 'false' is the
default value.
private static int lastIndex;
public static void main(String[] args) {
final JFrame frame = new JFrame();
Not inheritance?
More important: this is not on the EDT.
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JList list1 = new JList();
final JList list2 = new JList();
final DefaultListModel model = new DefaultListModel();
final DefaultListSelectionModel selectionModel =
new DefaultListSelectionModel();
selectionModel.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
selectionModel.addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (useLast) {
list1.setSelectedIndex(lastIndex);
list2.setSelectedIndex(lastIndex);
useLast = false;
}
}
});
JButton addButton=new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lastIndex = list1.getSelectedIndex();
useLast = true;
model.add(0, "AddedItem 0");
}
});
frame.add(list1, BorderLayout.WEST);
frame.add(list2, BorderLayout.EAST);
frame.add(addButton, BorderLayout.SOUTH);
list1.setModel(model);
list2.setModel(model);
list1.setSelectionModel(selectionModel);
list2.setSelectionModel(selectionModel);
for (int i = 0; i < 10; i++)
model.addElement(String.format("Item number %d", i));
SwingUtilities.invokeLater(new Runnable() {
And here you finally push code onto the EDT, but the construction was not.
//@Override
public void run() {
frame.setSize(500, 500);
frame.setVisible(true);
No call to 'pack()'.
}
});
}
}
</code>
--
Lew
---
* Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24