ListSelectionListener
リスト選択の変更時に発火するものを追加する必要があります。
jList1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
とでListSelectionEvent
private void jList1ValueChanged(ListSelectionEvent evt) {
if(!jList1.getValueIsAdjusting())
{
jTextField2.setText((String) jList1.getSelectedValue());
}
}
短い例を次に示します。
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListTest {
private JList jList1;
private JPanel jPanel1;
private JTextField jTextField2;
private JFrame frame;
public JListTest() {
initComponents();
}
private void initComponents() {
jPanel1 = new JPanel();
jList1 = new JList();
jTextField2 = new JTextField();
frame =new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jList1.setModel(new AbstractListModel() {
String[] strings = { "Computer", "Mouse", "HDD" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jTextField2.setText("jTextField1");
jPanel1.add(jList1);
jPanel1.add(jTextField2);
frame.add(jPanel1);
frame.pack();
frame.setVisible(true);
}
private void jList1ValueChanged(ListSelectionEvent evt) {
if(!jList1.getValueIsAdjusting())
{
jTextField2.setText((String) jList1.getSelectedValue());
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JListTest();
}
});
}
}