event
ListSelection example
With this tutorial we shall show you how to perform List Selection activities using JList
components and ListSelectionListener
interface. List selection is a very useful feature, when you applications requires user input with fixed choices.
In order to use JList and ListSelectionListener
, one should perform the following steps:
- Create a class that implements
ListSelectionListener
interface. - Override the methods that correspond to the events you want to monitor about the list e.g
valueChanged
and customize it to customize the handling of the respective event. - Create a new
JList
- Use the
addListSelectionListener
mehtod of theJList
class to add to it theListSelectionListener
you’ve created.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListSelectionExample extends JPanel { String labelArray[] = {"1", "2", "3"}; JCheckBox checkBoxArray[] = new JCheckBox[labelArray.length]; JList listLable = new JList(labelArray); public ListSelectionExample() { JScrollPane scrollPane = new JScrollPane(listLable); add(scrollPane); listLable.addListSelectionListener(new SelectionListen()); for (int i = 0; i < labelArray.length; i++) { checkBoxArray[i] = new JCheckBox("Option " + i); add(checkBoxArray[i]); } } public static void main(String args[]) { JFrame jFrame = new JFrame("Selection example"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setContentPane(new ListSelectionExample()); jFrame.pack(); jFrame.setVisible(true); } } class SelectionListen implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent evetn) { if ((!evetn.getValueIsAdjusting()) || (evetn.getFirstIndex() == -1)) { return; } for (int i = evetn.getFirstIndex(); i <= evetn.getLastIndex(); i++) { System.out.println(((JList) evetn.getSource()).isSelectedIndex(i)); } } }
This was an example on how how to perform List Selection activities using JList
components and ListSelectionListener
interface.