In this tutorial, we’ll build a simple Quotes App in Java using Swing for the graphical user interface (GUI).
The app will display a random quote from a collection of quotes every time the user clicks a button.
This is a great project to learn the basics of Java Swing, event handling, and randomization.
Table of Contents
Features of the Quotes App:
The app has a collection of quotes stored in an array.
When the user clicks the “Show Another Quote” button, a random quote is displayed.
The quotes will be shown in a JLabel with a button below to refresh the displayed quote.
The app uses JFrame to create the window, JButton for user interaction, and JLabel to display quotes.
Complete Code
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class QuotesApp extends JFrame { private JLabel quoteLabel; // Label to display the quote private JButton nextQuoteButton; // Button to show another quote private String[] quotes; // Array of quotes // Constructor to set up the app public QuotesApp() { setTitle("Quotes App"); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window // Initialize the quotes array with a set of quotes quotes = new String[]{ "The only limit to our realization of tomorrow is our doubts of today. – Franklin D. Roosevelt", "Do what you can, with what you have, where you are. – Theodore Roosevelt", "Success is not final, failure is not fatal: It is the courage to continue that counts. – Winston Churchill", "You define your own life. Don't let other people write your script. – Oprah Winfrey", "Life is what happens when you're busy making other plans. – John Lennon", "Believe you can and you're halfway there. – Theodore Roosevelt" }; // Create and configure the quote label quoteLabel = new JLabel(getRandomQuote()); quoteLabel.setFont(new Font("Serif", Font.ITALIC, 16)); quoteLabel.setHorizontalAlignment(SwingConstants.CENTER); quoteLabel.setVerticalAlignment(SwingConstants.CENTER); // Create the "Show Another Quote" button nextQuoteButton = new JButton("Show Another Quote"); nextQuoteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { quoteLabel.setText(getRandomQuote()); // Display a new random quote } }); // Set up the layout of the app setLayout(new BorderLayout()); add(quoteLabel, BorderLayout.CENTER); // Add the quote label in the center add(nextQuoteButton, BorderLayout.SOUTH); // Add the button at the bottom // Make the frame visible setVisible(true); } // Method to get a random quote from the array private String getRandomQuote() { Random random = new Random(); int randomIndex = random.nextInt(quotes.length); // Get a random index from the quotes array return "<html><div style='text-align: center;'>" + quotes[randomIndex] + "</div></html>"; // Return the quote formatted for multi-line display } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new QuotesApp()); } }
Explanation of the Code
1. Import Statements
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; javax.swing.*: Imports all Swing components, such as JFrame, JLabel, JButton, etc. java.awt.*: Imports layout managers and component positioning classes. java.awt.event.*: Imports event listener classes for handling button clicks. java.util.Random: Allows us to generate random numbers, which we use to select a random quote.
2. Class Declaration and Instance Variables
public class QuotesApp extends JFrame { private JLabel quoteLabel; private JButton nextQuoteButton; private String[] quotes; } JLabel quoteLabel: This label displays the current quote. JButton nextQuoteButton: A button to display another random quote. String[] quotes: An array of strings that contains the set of quotes.
3. Constructor
public QuotesApp() { setTitle("Quotes App"); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Initialize the quotes array quotes = new String[]{ // Array of quotes }; // Configure the quote label quoteLabel = new JLabel(getRandomQuote()); quoteLabel.setFont(new Font("Serif", Font.ITALIC, 16)); quoteLabel.setHorizontalAlignment(SwingConstants.CENTER); quoteLabel.setVerticalAlignment(SwingConstants.CENTER); // Create and add the "Show Another Quote" button nextQuoteButton = new JButton("Show Another Quote"); nextQuoteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { quoteLabel.setText(getRandomQuote()); // Change the quote when the button is clicked } }); // Set the layout and add components setLayout(new BorderLayout()); add(quoteLabel, BorderLayout.CENTER); add(nextQuoteButton, BorderLayout.SOUTH); // Make the window visible setVisible(true); }
Frame Setup:
setTitle("Quotes App"): Sets the title of the window. setSize(400, 200): Sets the window size to 400x200 pixels. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window is closed. setLocationRelativeTo(null): Centers the window on the screen.
Quotes Array:
We initialize an array of quotes (quotes[]), each of which will be randomly displayed when the button is clicked.
Quote Label Setup:
quoteLabel = new JLabel(getRandomQuote()): The label is initialized with a random quote from the array. setFont(new Font("Serif", Font.ITALIC, 16)): Sets the font of the label text. setHorizontalAlignment(SwingConstants.CENTER) and setVerticalAlignment(SwingConstants.CENTER): Align the text in the center of the window.
Button Setup:
nextQuoteButton = new JButton("Show Another Quote"): A button that the user clicks to get another random quote. addActionListener(): Adds an event listener to the button. When clicked, it triggers the getRandomQuote() method and updates the label with a new random quote.
Layout Setup:
setLayout(new BorderLayout()): Uses a BorderLayout manager to position the components. add(quoteLabel, BorderLayout.CENTER): Adds the quote label to the center of the window. add(nextQuoteButton, BorderLayout.SOUTH): Adds the button at the bottom of the window.
Visibility:
setVisible(true): Makes the frame visible.
4. getRandomQuote() Method
private String getRandomQuote() { Random random = new Random(); int randomIndex = random.nextInt(quotes.length); // Select a random index from the quotes array return "<html><div style='text-align: center;'>" + quotes[randomIndex] + "</div></html>"; // Return the selected quote }
Random Selection:
Random random = new Random(): Creates a Random object to generate random numbers. random.nextInt(quotes.length): Generates a random index between 0 and quotes.length - 1.
Return the Quote:
The selected quote is returned. The use of <html> and <div style='text-align: center;'> allows the label to render the quote with proper line breaks and center alignment in case of long quotes.
5. Main Method
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new QuotesApp()); } SwingUtilities.invokeLater(): Ensures the app is run on the Event Dispatch Thread (EDT), which is necessary for Swing applications to ensure thread safety. new QuotesApp(): Creates and launches an instance of the app.
Game Flow
The app opens with a window displaying a random quote from the collection.
The user can click the “Show Another Quote” button to display another random quote.
The quote label updates each time the button is clicked, showing a new random quote.
The app continues to function until the user closes the window.
Customization Ideas
You can extend or customize this basic app in several ways:
1. Add More Quotes
You can easily add more quotes to the quotes[] array by adding new string entries.
quotes = new String[]{ "New Quote 1", "New Quote 2", ... };
2. Customize the Appearance
You can modify the font, color, and background to improve the appearance:
Change Font:
quoteLabel.setFont(new Font("Arial", Font.BOLD, 18));
Change Text Color:
quoteLabel.setForeground(Color.BLUE);
Change Background Color:
getContentPane().setBackground(Color.LIGHT_GRAY);
3. Load Quotes from a File
You can load the quotes from a text file instead of hardcoding them in the program:
// Example to load quotes from a file try (BufferedReader reader = new BufferedReader(new FileReader("quotes.txt"))) { String line; while ((line = reader.readLine()) != null) { // Add each line as a new quote } } catch (IOException e) { e.printStackTrace(); }
Conclusion
In this tutorial, you've learned how to create a simple Quotes App using Java Swing. The app showcases:
Creating a GUI with Swing components (JFrame, JLabel, JButton).
Displaying random content from an array of strings.
Handling button clicks with event listeners.
Dynamic updating of components (changing the quote on each button click).
This is a beginner-friendly project, and you can further enhance it with more features like dynamic quote loading, category selection, or more sophisticated animations.
You can add animations or fade-in effects when the quote changes to make the UI more dynamic.
You could add categories for quotes (e.g., “Inspiration”, “Motivation”, “Life”) and allow the user to select a category before showing a random quote from that category.