I was wondering if there is a way to retrieve a list of all the elements that have been added to a JList. For example I would like JList to return an array or list of Strings or JLabels from a custom cell renderer.
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.
We also obtain the size or the number of items in the JList components. This can be done by calling JList 's getModel() method which return a ListModel object. From the ListModel we can get the items size, and we can iterate the entire items of the JList component.
JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.
You can use getModel method to get ListModel. And then use getElementAt
and getSize
method to build array or list or whatever you want.
Yes of course. You getElementAt()
with a loop.
Example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class Jlist {
JFrame frame;
JList<String> list;
JButton button;
public Jlist(){
init();
}
public void init(){
frame = new JFrame("Sample");
frame.setSize(300, 300);
frame.setLayout(new BorderLayout(30, 30));
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("A");
model.addElement("B");
model.addElement("C");
model.addElement("D");
model.addElement("E");
list = new JList<>();
list.setModel(model);
JScrollPane pane = new JScrollPane(list);
pane.setViewportView(list);
button = new JButton("Get");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
buttonActionPerformed();
}
});
frame.add(pane, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void buttonActionPerformed(){
for(int i = 0; i< list.getModel().getSize();i++){
System.out.println(list.getModel().getElementAt(i));
}
}
public static void main(String[] args) {
new Jlist();
}
}
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