CamChat

Code sample

HistoryList is a simple utility class for storing sent chat messages.
When the user presses the Up/Down arrows on his keyboard, his earlier messages are retrieved from a HistoryList and copied into the "send box" (a JTextPane).

This simple class stores generic Objects rather than Strings, so could also be used to store images, files, custom data objects etc.
/**
 * HistoryList.java
 * @version 1.0
 * @copyright Sofware Cottage 2004
 */
package com.sc.util;
import java.util.ArrayList;

/**
 * A wrapped ArrayList which remembers the index
 * of the last item retrieved
 * @author Gil Murray 
 */
public class HistoryList
{
   private ArrayList items;
   private int pointer = 0;

   public HistoryList()
   {
      this(6);
   }

   public HistoryList(int capacity)
   {
      items = new ArrayList(capacity);

      // add a null item to the end of the list
      // - this represents eg a blank line at the
      // end of the history
      items.add(null);
   }

   public void add(Object item)
   {
      // added items will be inserted just before the
      // final null item
      pointer = items.size() - 1;
      items.add(pointer, item);
      pointer++;
   }

   public Object get()
   {
      if (items.size() > 0)
         return items.get(pointer);
      else
         return null;
   }

   public Object getPrev()
   {
      pointer--; if (pointer < 0) pointer = 0;
      return items.get(pointer);
   }

   public Object getNext()
   {
      pointer++; if (pointer == items.size()) pointer--;
      return items.get(pointer);
   }

   public void clear()
   {
      items.clear();
      pointer = 0;
   }

   public int size()
   {
      return items.size();
   }

   public String toString()
   {
      return items + " pointer=" + pointer;
   }
}