// Michael Tartaglia
// ListSortDemo: Exemplifying the ListSort class, this program lets the user
//		input one number at a time, remove numbers, or reverse the displayed
//		sequence of numbers

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class ListSortDemo extends Applet
implements ActionListener {
   private boolean ERROR;						// ERROR CHECKING BOOLEAN
   private ListSort L = new ListSort();	// LIST SORT
   private TextArea text;						// RESULTS DISPLAY
   private TextField numField;				// ENTERED NUMBER
   private Button enterButton, flipButton, deleteButton;

   public void init() {
      setBackground(Color.white);

		// WRITE INSTRUCTIONS
      Label instruct = new Label("Input some numbers.");
		
		// CREATE AND DISPLAY FORM ELEMENTS
      text = new TextArea("",10,51,text.SCROLLBARS_VERTICAL_ONLY);
      text.setEditable(false);
      text.setBackground(Color.white);
      numField = new TextField(5);
      numField.setEditable(true);
      numField.addActionListener(this);
      enterButton = new Button("Enter");
      enterButton.addActionListener(this);
      flipButton = new Button("Reverse!");
      flipButton.addActionListener(this);
      deleteButton = new Button("Remove");
      deleteButton.setEnabled(true);
      deleteButton.addActionListener(this);
      add(instruct); add(numField); add(enterButton);
      add(deleteButton); add(flipButton); add(text);
   }

   public void actionPerformed(ActionEvent e) {
      ERROR = false;			//	RESET ERROR CHECK BOOLEAN TO "NONE HAPPENED"
      Object source = e.getSource();	// GET SOURCE OF ACTION... 
      double num;				// NUMBER TYPED
      if (source == numField || source == enterButton) {		// IF "ENTER" WAS HIT
         try {					// READ NUMBER, CHECK FOR CORRECT FORMAT
            num = Double.parseDouble(numField.getText());
            L.addItem(num);
         } catch (NumberFormatException nfe) {ERROR = true;}
      } else if (source == flipButton) L.flip();				// IF "REVERSE" WAS HIT
      else if (source == deleteButton) {							// IF "DELETE" WAS HIT
         try {					// DELETE ALL OCCURENCES OF NUMBER ENTERED
            num = Double.parseDouble(numField.getText());
            L.removeAllOfItem(num);
         } catch (NumberFormatException nfe) {ERROR = true;}
      }
      numField.setText("");	// RESET NUMBER ENTRY BOX
      repaint();
   }

   public void paint(Graphics g) {
      if (ERROR) text.setText("Error! Try again!\n");		// DISPLAY ERROR MESSAGE
      else if (L.isEmpty()) text.setText("No numbers in list!");
      else text.setText("Entered " +L.length()+ " numbers:\n");

      for (int i = 0; i < L.length(); i++)
         text.append(L.itemAt(i) + "\t");			// DISPLAY NUMBERS FROM LIST INTO BOX
   }
}