The Palindrome Applet



/* Applet that takes  a sentence and answers if it is a palindrome
*/

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Palindrome extends Applet implements ActionListener
{

	// GUI variables
		Label enterLabel = new Label("Enter a sentence...", Label.LEFT);
		TextField enterField = new TextField(60);
		Button goButton = new Button("Is it a Palindrome?");
		
	// Program Variables
	String Sentence, cleanSentence;
	boolean valid = false;
	
	public void init() {
		makeGUI();
	}
	
	public void paint( Graphics g ) {
		int x = 20, y = 20;
		if (valid) {
			// Draw the sentence
			g.drawString("Sentence = " + Sentence, x, y+= 20);
		
			g.drawString("Clean Sentence = " + cleanSentence, x, y+= 20);
			
			// is it a palindrome?
			if (isPalindrome(cleanSentence))
				g.drawString("It is a palindrome!", x, y+= 20);
			else
				g.drawString("It is not a palindrome.", x, y+=20);
		}
	} // paint

	public boolean isPalindrome(String s) {
		for (int Left=0, Right = s.length()-1; Left < Right; Left++, Right--) {
			if (s.charAt(Left) != s.charAt(Right))
				return false;
		}
		return true;
	} // isPalindrome
	
	public void processSentence() {
		Sentence = enterField.getText();			// get the sentence
		
		// Clean up the sentence
		// 1. convert it all to lower case
		cleanSentence = Sentence.toLowerCase();
		
		// 2. remove all non alphabetic characters from it
		// Convert cleanSentence into a character array
		char [ ] cs = cleanSentence.toCharArray();
		int L = cs.length;
		
		// Remove all non-alpha from character array
		for (int i=0; i < L; i++) {
			// if ith char in cs is not alpha, remove it
			if (!isAlpha(cs[i])) {
				// remove ith character
				for (int j=i+1; j < L; j++)
					cs[j-1] = cs[j];
				// decrease the length by 1
				L--;
				i--;
			}
		}
		
		// convert character array back into a string
		cleanSentence = new String(cs, 0, L);
		
		valid = true;
	} // processSentence
	
	boolean isAlpha(char c) {
		return (c >= 'a' && c <= 'z');
	} // isAlpha
	
	public void actionPerformed(ActionEvent e) {
	
		if (e.getSource() == goButton)			// New way to check for button
			processSentence();
			
		repaint();
	} // actiopPerformed
	
	public void makeGUI() {
		// Create a 3x1 panel
		Panel p = new Panel();
		p.setLayout(new GridLayout(3,1));
		
		// Draw the Label
		p.add(enterLabel);
		
		// Draw the TextField
		Panel ePanel = new Panel();
		ePanel.add(enterField);
		p.add(ePanel);
		
		// Draw the Button
		Panel bPanel = new Panel();
		bPanel.add(goButton);
		p.add(bPanel);
		
		p.setBackground(Color.cyan);
		
		// applet layout
		this.setLayout(new BorderLayout());
		this.add(p, "South");
		
		// Register Listener
		goButton.addActionListener(this);
	} // makeGUI
}