What you’re looking for is a System that checks when you’ve changed the selected element within your Jlist.
You can make your Jlist implement a Listselectionlistener, and overwrite the method 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.
Prior: