In this tutorial, we will build a simple Palindrome Checker in Java using Swing for the graphical user interface (GUI).
A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).
Features:
Allows users to input text into a text field.
Checks if the input text is a palindrome, ignoring case, spaces, and punctuation.
Displays a result indicating whether the text is a palindrome.
Provides a Check button to trigger the check.
Complete Code
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class PalindromeCheckerApp extends JFrame { private JTextField inputField; // Text field for user input private JButton checkButton; // Button to check for palindrome private JLabel resultLabel; // Label to display the result // Constructor to set up the GUI public PalindromeCheckerApp() { setTitle("Palindrome Checker"); setSize(600, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window on the screen // Create input field inputField = new JTextField(20); // Create check button checkButton = new JButton("Check Palindrome"); // Create result label resultLabel = new JLabel("Enter text to check if it's a palindrome.", SwingConstants.CENTER); resultLabel.setFont(new Font("Serif", Font.BOLD, 16)); // Panel to hold input and button JPanel inputPanel = new JPanel(); inputPanel.add(new JLabel("Enter text:")); inputPanel.add(inputField); inputPanel.add(checkButton); // Set layout for the frame setLayout(new BorderLayout()); add(inputPanel, BorderLayout.NORTH); add(resultLabel, BorderLayout.CENTER); // Add action listener to the button checkButton.addActionListener(new CheckButtonListener()); setVisible(true); } // Method to check if a given string is a palindrome private boolean isPalindrome(String text) { // Remove non-alphanumeric characters and convert to lowercase String cleanedText = text.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Check if the cleaned text is the same when reversed int left = 0; int right = cleanedText.length() - 1; while (left < right) { if (cleanedText.charAt(left) != cleanedText.charAt(right)) { return false; } left++; right--; } return true; } // Action listener for the Check button private class CheckButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String inputText = inputField.getText(); if (isPalindrome(inputText)) { resultLabel.setText("Yes! '" + inputText + "' is a palindrome."); } else { resultLabel.setText("No! '" + inputText + "' is not a palindrome."); } } } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new PalindromeCheckerApp()); } }
Explanation of the Code
1. Import Statements
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; javax.swing.*: Provides Swing components such as JFrame, JButton, JTextField, and JLabel to create the GUI. java.awt.*: Provides layout and graphical utilities like BorderLayout and Font. java.awt.event.*: Provides event listener classes for handling button click events.
2. Class Declaration and Instance Variables
public class PalindromeCheckerApp extends JFrame { private JTextField inputField; // Text field for user input private JButton checkButton; // Button to check for palindrome private JLabel resultLabel; // Label to display the result } JTextField inputField: A text field where the user can input the text to check. JButton checkButton: A button that the user clicks to trigger the palindrome check. JLabel resultLabel: A label that displays the result of the palindrome check.
3. Constructor
public PalindromeCheckerApp() { setTitle("Palindrome Checker"); setSize(600, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window on the screen // Create input field inputField = new JTextField(20); // Create check button checkButton = new JButton("Check Palindrome"); // Create result label resultLabel = new JLabel("Enter text to check if it's a palindrome.", SwingConstants.CENTER); resultLabel.setFont(new Font("Serif", Font.BOLD, 16)); // Panel to hold input and button JPanel inputPanel = new JPanel(); inputPanel.add(new JLabel("Enter text:")); inputPanel.add(inputField); inputPanel.add(checkButton); // Set layout for the frame setLayout(new BorderLayout()); add(inputPanel, BorderLayout.NORTH); add(resultLabel, BorderLayout.CENTER); // Add action listener to the button checkButton.addActionListener(new CheckButtonListener()); setVisible(true); }
Frame Setup:
setTitle(“Palindrome Checker”): Sets the window title.
setSize(400, 150): Sets the size of the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.
Input Field and Button Setup:
inputField = new JTextField(20): Creates the input field where the user can type text.
checkButton = new JButton(“Check Palindrome”): Creates the button that the user clicks to check if the input text is a palindrome.
Result Label Setup:
resultLabel = new JLabel(…): Initializes the label that will display the result.
resultLabel.setFont(new Font(“Serif”, Font.BOLD, 16)): Sets the font style and size for the label.
Layout Setup:
setLayout(new BorderLayout()): Uses a border layout to position components.
add(inputPanel, BorderLayout.NORTH): Adds the input panel (containing the input field and button) to the top of the window.
add(resultLabel, BorderLayout.CENTER): Adds the result label to the center of the window.
Button Action Listener:
checkButton.addActionListener(new CheckButtonListener()): Registers an action listener to handle button click events.
4. isPalindrome() Method
private boolean isPalindrome(String text) { // Remove non-alphanumeric characters and convert to lowercase String cleanedText = text.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Check if the cleaned text is the same when reversed int left = 0; int right = cleanedText.length() - 1; while (left < right) { if (cleanedText.charAt(left) != cleanedText.charAt(right)) { return false; } left++; right--; } return true; }
Cleaning the Input:
text.replaceAll(“[^a-zA-Z0-9]”, “”): Removes all non-alphanumeric characters (punctuation, spaces, etc.).
toLowerCase(): Converts the cleaned text to lowercase to make the check case-insensitive.
Checking for Palindrome:
The method uses two pointers (left and right) to compare characters from the start and end of the string.
If any mismatch is found, the method returns false; otherwise, it returns true when all characters match.
5. Action Listener for the Check Button
private class CheckButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String inputText = inputField.getText(); if (isPalindrome(inputText)) { resultLabel.setText("Yes! '" + inputText + "' is a palindrome."); } else { resultLabel.setText("No! '" + inputText + "' is not a palindrome."); } } }
Checking for Palindrome:
inputField.getText(): Retrieves the text entered by the user.
isPalindrome(inputText): Calls the method to check if the entered text is a palindrome.
Displaying the Result:
If the input text is a palindrome, the label is updated with a success message.
If it is not a palindrome, the label is updated with a failure message.
6. Main Method
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new PalindromeCheckerApp()); } SwingUtilities.invokeLater(): Ensures that the GUI is created and updated on the Event Dispatch Thread (EDT), which is necessary for Swing applications. new PalindromeCheckerApp(): Creates and launches the palindrome checker app.
Customization Ideas
1. Handle Multiple Lines of Text
Allow the user to enter multiple lines of text and check if the entire paragraph is a palindrome.
2. Display More Detailed Information
Display additional information such as the cleaned text, the reverse of the text, and how many characters were removed during cleaning.
3. Improve the User Interface
Customize the appearance of the app by changing fonts, adding colors, and using icons.
Conclusion
This Palindrome Checker in Java using Swing is a simple and effective application to demonstrate how to use a graphical interface for checking if text is a palindrome. The key concepts covered include:
Using Swing components like JFrame, JButton, JTextField, and JLabel.
Implementing event-driven programming with action listeners.
String manipulation to clean and reverse the input text for palindrome checking.
You can extend this project by adding more features and improving the user interface.