import java.awt.Graphics;
import java.util.*;
import javax.swing.*;

/**
 * An example of a Component that supports text drag-and-drop.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version Drop Only; Standard Handler
 */
public class StringCollage extends JPanel
{
  private static final long serialVersionUID = 1L;

  private List<StringContent>       elements;
  
  /**
   * Default Constructor.
   */
  public StringCollage()
  {
    super();
    elements = new ArrayList<StringContent>();
    
    // Use a bean-oriented handler for objects with a text property
    // (i.e., with getText() and setText() methods)
    setTransferHandler(new TransferHandler("text"));
  }
  
  // Methods required to be a "text" bean
  
  /**
   * Get the text on this Component.
   * 
   * This method is required so that this is a bean with the text property.
   * 
   * @return The text of the last element
   */
  public String getText()
  {
    return elements.get(elements.size()-1).getText();
  }
  
  /**
   * Add a new piece of text to this Component at a random location.
   * 
   * @param The text (tab delimited)
   */
  public void setText(String s)
  {
    setText(s, (int)(Math.random()*getWidth()), (int)(Math.random()*getHeight()));
    repaint();
  }

  // Methods that provide the desired GUI functionality

  /**
   * Render this Component.
   * 
   * @param g  The rendering engine to use.
   */
  public void paint(Graphics g)
  {
    super.paint(g);
    for (StringContent e: elements)
    {
      g.drawString(e.getText(), e.getLocation().x, e.getLocation().y);
    }
  }

  /**
   * Set text on this element at the given location.
   * 
   * @param text  The text to add
   * @param x     The x-coordinate
   * @param y     The y-coordinate
   */
  public void setText(String text, int x, int y)
  {
    elements.add(new StringContent(text, x, y));
  }
}
