Swing JList Class



Swing JList Class :

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class JListDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JListDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("JList Demo", JLabel.CENTER);
    msgLabel = new JLabel("Empty Selection", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JListDemo swingControlDemo = new JListDemo();
    swingControlDemo.showListDemo();
  }

  private void showListDemo() {

    final DefaultListModel languageNames = 
              new DefaultListModel();

    languageNames.addElement("Hindi");
    languageNames.addElement("English (USA)");
    languageNames.addElement("English (UK)");
    languageNames.addElement("Marathi");

    final JList langList = new JList(languageNames);
    langList.setSelectionMode
         (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    langList.setVisibleRowCount(5);

    JScrollPane fruitScrollPane = new JScrollPane(langList);

    JButton showButton = new JButton("Show Languages");

    showButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String list = "Languages Selected : ";
        if (langList.getSelectedIndex() != -1) {
          for (Object lang : langList.getSelectedValues()) {
            list += lang + "  ";
          }
        }
        msgLabel.setText(list);
      }
    });

    mainPanel.add(fruitScrollPane);
    mainPanel.add(showButton);
    mainFrame.setVisible(true);
  }
}

Output :

JList