Sep 27

The following example shows one way of creating a nested JList using Swing whereby selecting an item in the first list will display a different set of options in the second list depending on what has been selected in the first list.


import java.awt.GridLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class NestedList extends JPanel
	implements ListSelectionListener
{
	private DefaultListModel model = new DefaultListModel();
	
	private JList list1 = new JList(model);
	private JList list2 = new JList();

	private NestedList()
	{
		super(new GridLayout(0, 2));
		add(list1);
		add(list2);
		
		list1.addListSelectionListener(this);
	}
	
	public void addItem(String item, String[] subitems)
	{
		model.addElement(new NestedItem(item, subitems));
	}
	
	public void valueChanged(ListSelectionEvent e)
	{
		NestedItem item = 
                   (NestedItem) list1.getSelectedValue();
		list2.setModel(item.subitems);
	}

	private static class NestedItem
	{
		private String item = null;
		private DefaultListModel subitems = 
                   new DefaultListModel();
		
		NestedItem(String item, String[] subitems)
		{
			this.item = item;
			for (String subitem : subitems)
			this.subitems.addElement(subitem);
		}
		
		public String toString()
		{
			return item;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		JFrame frame = new JFrame("Nested Lists");
		frame.setDefaultCloseOperation(
                    JFrame.DISPOSE_ON_CLOSE);
		NestedList list = new NestedList();
		list.addItem("numbers", 
                   new String[] { "1", "2", "3" });
		list.addItem("letters", 
                   new String[] { "A", "B", "C" });
		list.addItem("symbols", 
                   new String[] { "+", "=", ">", "?" });
		frame.add(list);
		frame.pack();
		frame.setVisible(true);
	}
}

written by objects


Leave a Reply

You must be logged in to post a comment.