What you are looking for is a listener that checks when you have changed the selected element within your JList.
You can have your JList implement a ListSelectionListener , and overwrite the valueChanged()
.
Example:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JList;
import javax.swing.JLabel;
public class Lista extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel lblNewLabel;
private JList<String> list;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lista frame = new Lista();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Lista() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.SOUTH);
list = new JList<String>();
list.setListData(new String[]{"Cachorro", "Elefante", "Gato"});
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
System.out.println(e);
if (list.getSelectedValue() != null) {
lblNewLabel.setText(list.getSelectedValue().toString());
}
}
});
contentPane.add(list, BorderLayout.CENTER);
}
}
Every time you change the JList element it updates the JLabel below it.
Preview: