jlist
JList is a Swing component with which we can display a list of elements. This component also allows the user to select one or more elements visually.
A JList presents the user with a group of items, displayed in one or more columns, to choose from. Lists can have many items, so they are often put in scroll panes.
Initializing a List
list = new JList(data);
Adding Items to and Removing Items from a List
ListDemo code that creates a mutable list model object, puts the initial items in it, and uses the list model to create a list
listModel = new DefaultListModel(); listModel.addElement("Jane Doe"); listModel.addElement("John Smith"); listModel.addElement("Kathy Green"); list = new JList(listModel);
import java.awt.Color; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListLocation extends JFrame { private JList<String> list; private static String[] colorname = {"black", "blue", "red", "white"}; private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE}; public ListLocation() { super("title"); FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.LEFT); list = new JList<String>(colorname); list.setVisibleRowCount(10); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setLayout(layout); add(list); list.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { getContentPane().setBackground(colors[list.getSelectedIndex()]); } } ); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 800); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { new ListLocation(); } catch (Exception e) { e.printStackTrace(); } } }); } }