Monday , December 11 2017
Home / java / Java Swing JList Example

Java Swing JList Example

In this tutorials, we are going to learn about Java Swing JList component. JList is a component used to display a list of objects that allows the user to select one or more items.

Swing JList Example :

In this example I am going to create a Colors list, and apply the background color by selecting the list item.


package com.onlinetutorialspoint.swing;

import java.awt.Color;
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 {
    private JList jList;
    // Creating list items
    private static final String[] listItems = { "BLUE", "BLACK", "CYAN",
            "GREEN", "GRAY", "RED", "WHITE" };
    // Creating colors
    private static final Color[] colors = { Color.BLUE, Color.BLACK,
            Color.CYAN, Color.GREEN, Color.GRAY, Color.RED, Color.WHITE };

    public JListDemo() {
        super("JList Demo");
        setLayout(new FlowLayout());

        jList = new JList(listItems);
        
        // set to single selection mode
        jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // limit the visible row count of JList
        
        jList.setVisibleRowCount(4);
        add(new JScrollPane(jList));
        
        jList.addListSelectionListener(new ListSelectionListener() {
            
            @Override
            public void valueChanged(ListSelectionEvent e) {
                getContentPane().setBackground(colors[jList.getSelectedIndex()]);
            }
        });
        
    }
    public static void main(String[] args) {
        JListDemo jListDemo = new JListDemo();
        jListDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jListDemo.setSize(350, 150);
        jListDemo.setVisible(true);
    }
}

Output :

Swing JList 1

Selected List Item with Green :

Swing JList 2

Changed the List Item with Gray:

Swing JList 3

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java Graphics2D Class Example

In this tutorials, we are going to see how to use Java Graphics2D class. Java …

Leave a Reply

Your email address will not be published. Required fields are marked *