Java Swing How to - Create JList from DefaultListModel








Question

We would like to know how to create JList from DefaultListModel.

Answer

//from  w  w  w.j  ava  2 s  .  co m
import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class Main {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}