Get item value in focus on a Jlist?

Asked

Viewed 1,392 times

2

I have a Jlist and would like to take the value of the item that is in focus on it, not want to capture this value with click or with some button, but rather just changing the focus(by clicking on the item or with the arrows p/ up or p/ down). For example: A Jlist with a list of animals, whenever an item is selected wanted to take the information of the animal so that it is not necessary to click on the name of the animal, only by the focus. I know the question is confused but any doubt question I try to explain better.

1 answer

2


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:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.