Flashcards in Java

Written By: James Williams

- 10 Apr 2006 -
















Description: By using Java and XML, this tutorial walks you through creating flashcards for learning French.

  1. Introduction
  2. The User Interface
  3. ActionListener/MouseListeners
  4. Loading the Word List

The User Interface

For simplicity, the user interface will consist of a single window with a single label and menu bar...and will done by hand. Netbeans is a great IDE but it generates a lot of additional code. Very useful in a production environment but very hard to make heads or tails of when you are trying to learn. We have already created a top-level FlashCardApp class that extends JFrame and imports all the required namespaces.

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import java.util.*;                       
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
 
public class FlashCardApp extends JFrame {
        public static void main(String [] args) {
                //creates an instance of the app and shows the JFrame
                new FlashCardApp().setVisible(true);
        }
        
        public FlashCardApp() {
 
        }
}

If we compile and run the application right now, the window would be nameless and the minimum size. Not very useful at all. Let's use the constructor to set some of the window attributes, like the title, size, and default close action which determines if closing the window just closes the window or closes the application.

         setTitle("Flash Cards");
                //when we close this window, it will exit the application
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setSize(400,300);

Better. We have a title, a reasonable size, and an application that won't run forever after the window is closed. Now for some menus. We are going to need a File menu, Options for setting the few preferences we will have and a Help menu.

         JMenuBar menubar = new JMenuBar();
                JMenu fileMenu = new JMenu("File");
                JMenu optMenu = new JMenu("Options");
                JMenu helpMenu = new JMenu("Help");
                menubar.add(fileMenu);
                menubar.add(optMenu);
                menubar.add(helpMenu);
                setJMenuBar(menubar);

Now we have menus but no menu items. Let's create them and add them to our menus. It's pretty straight forward, so no need to explain.

         //menu items
                //File menu
                JMenuItem start = new JMenuItem("Start");
                JMenuItem loadList = new JMenuItem("Load Word List");
                JMenuItem exit = new JMenuItem("Exit");
                ...
                ...
                ...
                helpMenu.add(about);

<< Previous

Next >>