Find selected item of a JList and display it in real time

sharon Hwk picture sharon Hwk · Dec 10, 2012 · Viewed 72.9k times · Source

I have a JList, where i am displaying some ID's. I want to capture the ID the user clicked and dis play it on a JLabel.

String selected = jlist.getSelectedItem().toString();

The above code gives me the selected JList value. But this code has to be placed inside a button event, where when i click the button it will get the JList value an assign it to the JLabel.

But, what i want to do is, as soon as the user clicks an item of the JList to update the JLabel in real time. (without having to click buttons to fire an action)

Answer

Vinay picture Vinay · Dec 10, 2012

A simple example would be like below using listselectionlistener

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListDemo extends JFrame {

    public JListDemo() {

        setSize(new Dimension(300, 300));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        final JLabel label = new JLabel("Update");
        String[] data = { "one", "two", "three", "four" };
        final JList dataList = new JList(data);

        dataList.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent arg0) {
                if (!arg0.getValueIsAdjusting()) {
                  label.setText(dataList.getSelectedValue().toString());
                }
            }
        });
        add(dataList);
        add(label);

        setVisible(true);

    }

    public static void main(String args[]) {
        new JListDemo();
    }

}