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)
The selection mode can be changed on the selection model directly, or via JList 's cover method.
Multiple selection list enables the user to select many items from a JList. A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by clicking the first item, then holding the Shift key while clicking the last item to select in the range.
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();
}
}
Why don't you put a ListSelectionListener
on your JList
, and add your above code in to it.
I'm assuming you already know how to create listeners on JButtons, based on your question, so you just need to tweak it to create a ListSelectionListener
instead, then assign the listener to your JList
using jlist.addListSelectionListener(myListener);
There is a nice tutorial here that should get you started, or refer to the documentation
You should be aiming for something like this...
jlist.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()){
JList source = (JList)event.getSource();
String selected = source.getSelectedValue().toString();
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With