Java Swing Tutorial - Java DefaultListModel .setElementAt (E element, int index)








Syntax

DefaultListModel.setElementAt(E element, int index) has the following syntax.

public void setElementAt(E element,  int index)

Example

In the following code shows how to use DefaultListModel.setElementAt(E element, int index) method.

/*  www .ja v  a  2s .  c om*/

import java.awt.BorderLayout;
import java.util.Enumeration;

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

public class Main {

  public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(1000);
    for (int i = 0; i < 100; i++) {
      for (int j = 0; j < 5; j++) {
        model.addElement(labels[j]);
      }
    }
    model.setElementAt("0",0);
    
    
    JList jlist2 = new JList(model);
    jlist2.setVisibleRowCount(4);
    jlist2.setFixedCellHeight(12);
    jlist2.setFixedCellWidth(200);
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);

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