Creating a Basic Random Word Generator in Java — A Step by Step Tutorial
Introduction
In this tutorial, I will walk you through every step of the process of creating a random word generator using Java. This beginner-friendly guide will introduce you to Java Lists and the Swing library for creating graphical user interfaces (GUIs). By the end of this tutorial, you will have built a fully functional random word generator that allows users to generate, add, remove, and display words in a list.
If you’d like to jump straight to the complete code example, feel free to scroll down to the end of this article.
Prerequisites:
- Basic knowledge of Java programming
- Java Development Kit (JDK) installed
Step 1: Set up the project and import libraries
Create a new Java project and a class named Main
. In the Main
class, import the necessary libraries:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
}
}
Step 2: Create the main window and panel
Initialize a JFrame
object to create the main window, and set its properties:
JFrame frame = new JFrame("Random Word Generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
Create a JPanel
object to hold the components and add it to the main window:
JPanel panel = new JPanel();
frame.add(panel);
Step 3: Create components and add them to the panel
Create the necessary components for the GUI:
- A
JLabel
for the welcome message JButton
objects for generating, adding, removing, and displaying words, and clearing the output- A
JTextArea
to display the output - A
JScrollPane
to make the output scrollable
JLabel welcomeLabel = new JLabel("Welcome to the random word generator!");
JButton generateButton = new JButton("Generate a random word");
JButton addButton = new JButton("Add a new word");
JButton removeButton = new JButton("Remove a word");
JButton showAllButton = new JButton("Show all words");
JButton clearOutputButton = new JButton("Clear Output");
JTextArea outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
Add the components to the panel:
panel.add(welcomeLabel);
panel.add(generateButton);
panel.add(addButton);
panel.add(removeButton);
panel.add(showAllButton);
panel.add(clearOutputButton);
panel.add(scrollPane);
Step 4: Set the layout for the panel
Define a GroupLayout
object to manage the layout of the components in the panel:
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
Set the horizontal and vertical layouts for the components:
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(welcomeLabel)
.addComponent(generateButton)
.addComponent(addButton)
.addComponent(removeButton)
.addComponent(showAllButton)
.addComponent(clearOutputButton)
.addComponent(scrollPane)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(welcomeLabel)
.addComponent(generateButton)
.addComponent(addButton)
.addComponent(removeButton)
.addComponent(showAllButton)
.addComponent(clearOutputButton)
.addComponent(scrollPane)
);
Step 5: Initialize the list and random generator
Create a List<String>
object to store the words, and a Random
object for generating random numbers:
List<String> myList = new ArrayList<>();
myList.add("avenue");
myList.add("splurge");
myList.add("stretch");
myList.add("market");
Random r = new Random();
Step 6: Add action listeners for the buttons
Define ActionListener
objects for each button to perform the desired actions, such as generating random words, adding new words, removing words, showing all words, and clearing the output:
generateButton.addActionListener(/* ... */);
addButton.addActionListener(/* ... */);
removeButton.addActionListener(/* ... */);
showAllButton.addActionListener(/* ... */);
clearOutputButton.addActionListener(/* ... */);
Generate Button:
generateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Generate and display a random word
int randomItem = r.nextInt(myList.size());
String randomElement = myList.get(randomItem);
outputArea.append("Random word: " + randomElement + "\n");
}
});
In this section of the code, we are adding an action listener to the “Generate” button. An action listener is a type of event handler that listens for specific events (in this case, button clicks) and performs a specific action when the event occurs.
generateButton.addActionListener(new ActionListener() {
creates an anonymous inner class that implements the ActionListener
interface. This interface requires us to implement a single method: public void actionPerformed(ActionEvent e)
.
The actionPerformed
method is called whenever the button is clicked. In this method, we perform the following actions:
- Generate a random integer between 0 (inclusive) and the size of the word list (exclusive) using the
nextInt()
method from theRandom
class:int randomItem = r.nextInt(myList.size());
- Retrieve the word from the list at the index corresponding to the randomly generated integer:
String randomElement = myList.get(randomItem);
- Append the retrieved random word to the
outputArea
(aJTextArea
component) along with a label "Random word: " and a newline character:outputArea.append("Random word: " + randomElement + "\n");
This section of the code listens for clicks on the “Generate” button, and when clicked, it generates a random word from the list and displays it in the output area.
Add Button:
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Prompt the user for a new word and add it to the list
String newWord = JOptionPane.showInputDialog("Enter the new word:");
if (newWord != null && !newWord.trim().isEmpty()) {
myList.add(newWord);
outputArea.append("Word added: " + newWord + "\n");
}
}
});
In this section of the code, we are adding an action listener to the “Add” button.
addButton.addActionListener(new ActionListener() {
creates an anonymous inner class that implements the ActionListener
interface. The ActionListener
interface requires the implementation of a single method: public void actionPerformed(ActionEvent e)
.
The actionPerformed
method is called whenever the "Add" button is clicked. In this method, we perform the following actions:
- Display an input dialog to prompt the user for a new word using the
showInputDialog()
method from theJOptionPane
class:String newWord = JOptionPane.showInputDialog("Enter the new word:");
- Check if the user input is not null and not empty after trimming any whitespace:
if (newWord != null && !newWord.trim().isEmpty()) {
- If the input is valid, add the new word to the list:
myList.add(newWord);
- Append the added word to the
outputArea
(aJTextArea
component) along with a label "Word added: " and a newline character:outputArea.append("Word added: " + newWord + "\n");
This code listens for clicks on the “Add” button, and when clicked, it prompts the user for a new word, adds the word to the list, and displays a confirmation message in the output area.
Remove Button:
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Prompt the user for a word to remove and remove it from the list
String wordToRemove = JOptionPane.showInputDialog("Enter the word to remove:");
if (wordToRemove != null) {
if (myList.remove(wordToRemove)) {
outputArea.append("Word removed: " + wordToRemove + "\n");
} else {
outputArea.append("Word not found: " + wordToRemove + "\n");
}
}
}
});
In this section of the code, we are attaching an action listener to the “Remove” button.
removeButton.addActionListener(new ActionListener() {
creates an anonymous inner class that implements the ActionListener
interface. The ActionListener
interface requires the implementation of a single method: public void actionPerformed(ActionEvent e)
.
The actionPerformed
method is called whenever the "Remove" button is clicked. In this method, we perform the following actions:
- Display an input dialog to prompt the user for a word to remove using the
showInputDialog()
method from theJOptionPane
class:String wordToRemove = JOptionPane.showInputDialog("Enter the word to remove:");
- Check if the user input is not null:
if (wordToRemove != null) {
- Attempt to remove the inputted word from the list using the
remove()
method. The method returnstrue
if the word was successfully removed, andfalse
otherwise:if (myList.remove(wordToRemove)) {
- If the word was removed, append a confirmation message to the
outputArea
(aJTextArea
component) with the label "Word removed: " and a newline character:outputArea.append("Word removed: " + wordToRemove + "\n");
- If the word was not found in the list, append an error message to the
outputArea
with the label "Word not found: " and a newline character:outputArea.append("Word not found: " + wordToRemove + "\n");
This section of the code listens for clicks on the “Remove” button, and when clicked, it prompts the user for a word to remove, attempts to remove the word from the list, and displays either a confirmation or error message in the output area depending on the outcome.
Show All Words Button:
showAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Display all the words in the list
outputArea.append("All words:\n");
for (String word : myList) {
outputArea.append(word + "\n");
}
}
});
In this section of the code, we are attaching an action listener to the “Show all words” button.
showAllButton.addActionListener(new ActionListener() {
creates an anonymous inner class that implements the ActionListener
interface. The ActionListener
interface requires the implementation of a single method: public void actionPerformed(ActionEvent e)
.
The actionPerformed
method is called whenever the "Show all words" button is clicked. In this method, we perform the following actions:
- Append a label “All words:” followed by a newline character to the
outputArea
(aJTextArea
component):outputArea.append("All words:\n");
- Iterate through each word in the list
myList
using a for-each loop:for (String word : myList) {
- For each word, append the word followed by a newline character to the
outputArea
:outputArea.append(word + "\n");
In summary, this section of the code listens for clicks on the “Show all words” button, and when clicked, it displays all the words in the list in the output area, one word per line. This provides the user with a clear and organized view of the words currently stored in the list.
Clear Output Button:
clearOutputButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear the text in the output area
outputArea.setText("");
}
});
In this part of the code, we are attaching an action listener to the “Clear Output” button.
clearOutputButton.addActionListener(new ActionListener() {
creates an anonymous inner class that implements the ActionListener
interface. The ActionListener
interface requires the implementation of a single method: public void actionPerformed(ActionEvent e)
.
The actionPerformed
method is called whenever the "Clear Output" button is clicked. In this method, we perform the following action:
- Clear the text in the
outputArea
(aJTextArea
component) by setting its text to an empty string:outputArea.setText("");
The code here listens for clicks on the “Clear Output” button, and when clicked, it clears the content of the output area by setting its text to an empty string. This functionality allows the user to clear the output area’s content, making it easier to read and understand the output of subsequent actions.
Step 7: Display the main window
Finally, make the main window visible:
frame.setVisible(true);
Final Code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
// Create the main window with a title, size, and close operation
JFrame frame = new JFrame("Random Word Generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Create the main panel to hold all components
JPanel panel = new JPanel();
frame.add(panel);
// Create the components for the GUI
JLabel welcomeLabel = new JLabel("Welcome to the random word generator!");
JButton generateButton = new JButton("Generate a random word");
JButton addButton = new JButton("Add a new word");
JButton removeButton = new JButton("Remove a word");
JButton showAllButton = new JButton("Show all words");
JButton clearOutputButton = new JButton("Clear Output");
JTextArea outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
// Add the components to the main panel
panel.add(welcomeLabel);
panel.add(generateButton);
panel.add(addButton);
panel.add(removeButton);
panel.add(showAllButton);
panel.add(clearOutputButton);
panel.add(scrollPane);
// Set the layout for the main panel using GroupLayout
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(welcomeLabel)
.addComponent(generateButton)
.addComponent(addButton)
.addComponent(removeButton)
.addComponent(showAllButton)
.addComponent(clearOutputButton)
.addComponent(scrollPane)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(welcomeLabel)
.addComponent(generateButton)
.addComponent(addButton)
.addComponent(removeButton)
.addComponent(showAllButton)
.addComponent(clearOutputButton)
.addComponent(scrollPane)
);
// Initialize the list of words and the random word generator
List<String> myList = new ArrayList<>();
myList.add("avenue");
myList.add("splurge");
myList.add("stretch");
myList.add("market");
Random r = new Random();
// Add action listeners for the buttons to handle user interactions
generateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Generate and display a random word
int randomItem = r.nextInt(myList.size());
String randomElement = myList.get(randomItem);
outputArea.append("Random word: " + randomElement + "\n");
}
});
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Prompt the user for a new word and add it to the list
String newWord = JOptionPane.showInputDialog("Enter the new word:");
if (newWord != null && !newWord.trim().isEmpty()) {
myList.add(newWord);
outputArea.append("Word added: " + newWord + "\n");
}
}
});
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Prompt the user for a word to remove and remove it from the list
String wordToRemove = JOptionPane.showInputDialog("Enter the word to remove:");
if (wordToRemove != null) {
if (myList.remove(wordToRemove)) {
outputArea.append("Word removed: " + wordToRemove + "\n");
} else {
outputArea.append("Word not found: " + wordToRemove + "\n");
}
}
}
});
showAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Display all the words in the list
outputArea.append("All words:\n");
for (String word : myList) {
outputArea.append(word + "\n");
}
}
});
// Add action listener for the clear output button
clearOutputButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear the text in the output area
outputArea.setText("");
}
});
// Show the main window
frame.setVisible(true);
}
}
Conclusion
Congratulations! You have now created a random word generator using Java Lists and the Swing library. You can further customize the appearance and functionality of your application by exploring more Swing components and event handling techniques. Happy coding!