import java.awt.*;
import java.applet.Applet;

public class DeleteKeyFix extends Applet {
  Button _asciiCodeButton;
  TextField _enteredText;
  TextField _asciiCodesText;

  public void init() { 
    setLayout(new BorderLayout());
  
    _asciiCodeButton = new Button("Print ASCII Codes Of Text");
    add("Center",_asciiCodeButton);

    Panel insidePanel = new Panel();
    add("North",insidePanel);
    
    insidePanel.setLayout(new GridLayout(2,2));
    insidePanel.add(new Label("Enter text here:"));
    _enteredText = new TextField();
    insidePanel.add(_enteredText);
    
    insidePanel.add(new Label("ASCII Code Equivalent:"));
    _asciiCodesText = new TextField();
    insidePanel.add(_asciiCodesText);
           
  }

  private void asciiCodeButtonClicked() {
    String asciiCodes = "";
    char asciiArray [] = _enteredText.getText().toCharArray();
    for (int i = 0; i < asciiArray.length; i++) {
      asciiCodes = asciiCodes + "[" + 
        (new Integer((int)asciiArray[i])).toString() + "]";
    }
    _asciiCodesText.setText(asciiCodes);
  }

  public boolean handleEvent(Event event) {
    if (event.target == _asciiCodeButton && event.id == Event.ACTION_EVENT) {
      asciiCodeButtonClicked();
      return true;
    }
    if (event.id == event.KEY_PRESS) {
      //System.out.println("Key:" + event.key);
      // The following gets rid of the DEL
      // (forward delete) key on the Mac...
      // other platforms don't have a problem
      // with this.. why is the Mac so screwed up!?
      //
      // The following gives the pseudo effect of
      // what should really happen when the forward
      // delete is pressed.  Unfortunately, the 
      // setText() method at the end sets the cursor to
      // the end of the line. 
      //
      // WARNING: If you are trying to fix this,
      // setCaretPosition() is only JDK 1.1
      //
      // You may just want to forget it and ignore
      // the keypress altogether if event.key == 127.
      // Simply return true; if this is your preferred solution.
      //
      if (event.key == 127) {
        String osName = 
          System.getProperty("os.name").toLowerCase();
        if (event.target instanceof TextComponent && osName.indexOf("mac") != -1) {
          TextComponent tf = (TextComponent)event.target;
          int start = tf.getSelectionStart();
          int end = tf.getSelectionEnd();
          String text = tf.getText();
          if (end - start == 0) {
            text = text.substring(0,start) + text.substring(end + 1,text.length());
          } else {
            text = text.substring(0,start) + text.substring(end,text.length());
          }
          tf.setText(text);
        }
        return true;
      } else {
        return super.handleEvent(event);
      }
    }

    return super.handleEvent(event);
  }


} // end of class