INTRODUCTION OF JLIST

Introduction of JList


JList

    JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.

    JList Constructor

    JList()

    Constructs a JList with an empty model.

    JList(ListModel dataModel)

    Constructs a JList that displays the elements in the specified, non-null model.

    JList(Object[] listData)

    Constructs a JList that displays the elements in the specified array.

    JList(Vector listData)

    Constructs a JList that displays the elements in the specified Vector

Example:List()

 
            
            package com.sdj;
            import java.awt.Color;
            import java.awt.Container;
            import java.awt.FlowLayout;
            import javax.swing.JFrame;
            import javax.swing.JList;
            import javax.swing.JScrollPane;
            import javax.swing.ListSelectionModel;
            import javax.swing.event.ListSelectionEvent;
            import javax.swing.event.ListSelectionListener;
            public class JListDemo extends JFrame
            {
                JList list;
                String[] listColorNames = { "SDJ J2SE", "SDJ J2EE", "SDJ STRUTS", " SDJ HIBERNATE","SDJ SPRING" };
                Color[] listColorValues = { Color.CYAN, Color.BLUE, Color.GREEN,Color.YELLOW, Color.WHITE };
                Container contentpane;
                public JListDemo()
                {
                    super("SDJ Different Color List");
                    contentpane = getContentPane();
                    contentpane.setLayout(new FlowLayout());
                    list = new JList(listColorNames);
                    list.setSelectedIndex(0);
                    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                    contentpane.add(new JScrollPane(list));
                    list.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e)
                        {
                            contentpane.setBackground(listColorValues[list.getSelectedIndex()]);
                        }
                    });
                    setSize(200, 200);
                    setVisible(true);
                }
                public static void main(String[] args)
                {
                    JListDemo test = new JListDemo();
                    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
            } 
            

Output:

Naming Convention
SDJ JList Demo