Get value of the item in focus in a JList?

2

I have a JList and would like to get the value of the item that is in focus in it, I do not want to capture this value with a click or button, but only by changing the focus (clicking on the item or with the up or down arrows). For example: A JList with a list of animals, whenever an item is selected, it wants to get the animal's information so that it does not need to click on the animal's name, just by focus. I know the question is confusing but any questions I ask that I try to explain better.

    
asked by anonymous 20.11.2015 / 18:48

1 answer

2

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:

    
20.11.2015 / 19:09