You can add the listener and then just query the currently selected index.
I did a sample for you, I hope you find it useful.
This is the relevant section:
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
Bear in mind that's not the only way to go, this is just an starting point for you.
Here's the complete working sample:
import java.util.Vector;
import java.util.Arrays;
import java.awt.BorderLayout;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class JListSample {
private Vector<String> data = new Vector<String>(
Arrays.asList( new String [] {
"one", "two", "three"
})
);
private JTextField nameTextField;
public static void main( String [] args) {
JListSample s = new JListSample();
s.run();
}
public void run() {
JFrame frame = new JFrame("Selection test");
frame.add( list(), BorderLayout.WEST );
frame.add( editPanel() );
frame.pack();
frame.setVisible( true );
}
private JComponent list() {
final JList list = new JList( data);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int i = list.getSelectedIndex();
nameTextField.setText( i >= 0 ? data.get( i ) : "" );
}
});
return new JScrollPane( list );
}
private JComponent editPanel() {
JPanel panel = new JPanel();
panel.add( new JLabel("Name:") );
nameTextField = new JTextField(10);
panel.add( nameTextField );
return panel;
}
}
This is what is displayed: