DefaultListModel: getSize() : DefaultListModel « javax.swing « Java by API






DefaultListModel: getSize()

 
import java.awt.BorderLayout;
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.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class MainClass extends JPanel {

  JList list;

  DefaultListModel model;

  int counter = 15;

  public MainClass() {
    setLayout(new BorderLayout());
    model = new DefaultListModel();
    list = new JList(model);
    JScrollPane pane = new JScrollPane(list);
    JButton addButton = new JButton("Add Element");
    JButton removeButton = new JButton("Remove Element");
    for (int i = 0; i < 15; i++)
      model.addElement("Element " + i);

    addButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        model.addElement("Element " + counter);
        counter++;
      }
    });
    removeButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (model.getSize() > 0)
          model.removeElementAt(0);
      }
    });

    add(pane, BorderLayout.NORTH);
    add(addButton, BorderLayout.WEST);
    add(removeButton, BorderLayout.EAST);
  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("List Model Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new MainClass());
    frame.setSize(260, 200);
    frame.setVisible(true);
  }
}

           
         
  








Related examples in the same category

1.DefaultListModel: add(int index, Object element)
2.DefaultListModel: addElement(Object obj)
3.DefaultListModel: clear()
4.DefaultListModel: insertElementAt(Object obj, int index)
5.DefaultListModel: remove(int index)
6.DefaultListModel: removeAllElements()
7.DefaultListModel: removeElementAt(int index)
8.DefaultListModel: removeRange(int fromIndex, int toIndex)
9.DefaultListModel: set(int index, Object element)
10.DefaultListModel: setElementAt(Object obj, int index)
11.JList: setFixedCellWidth(int width)
12.DefaultListModel: ensureCapacity(int count)