macdevcenter.com
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button Java Programming on the Mac

Adding Spell Checking to Your Swing Applications

by Daniel H. Steinberg
01/18/2002

In this article, I'll show you how to add spell checking to your Swing applications. Any JTextComponent can be spell-checked with ease on Mac OS X; this is just another example of how the Apple engineers have Java-enabled Mac technology to make it available to your applications. If you're writing cross-platform applications, your Windows users will never know what they're missing (although taunting them is allowed, and often encouraged). I am warning you now that you will get to the end of this article and want your money back, as adding spell-checking support is that easy.

I'm writing this piece in response to reader requests. Feel free to continue to email me your comments on past columns and suggestions for future ones at DSteinberg@core.com.

Installing the Needed Files

The hardest part about adding spell checking to your Swing applications is downloading and installing the necessary files. You'll need to be an ADC (Apple Developer Connection) member, at any level. You can join at the free online level and still download the JavaSpellingFramework.tar file that you need. You should be an ADC member anyways -- it's a great way to keep up to date with what's coming from Apple, and thus far, they've made a lot of the Java preview software available to the free online members as well. Go to http://connect.apple.com to join.

Once you are a member, log in and select "Download Software" from the choices at the left side of your screen. Click on "Java" and then download the Java Spelling Framework. So far so good. It comes as a .tar file. You can untar it by opening up a terminal window, navigating to where you downloaded the file and typing gnutar xvf JavaSpellingFramework.tar.

This creates a JavaSpellingFramework directory that contains a ReadMe and a .pkg file. Note: you may be tempted to use Stuffit Deluxe to open up the tar file; on my machine that resulted in a faulty installation that was a bit annoying. Start up the installer by double-clicking on the JavaSpellingFramework.pkg file and following the instructions. You have now installed the Spelling framework.

The Frame For the Spell-checking Example

We'll begin by creating an application that looks like this:

Blank example

The cyan area is a JTextPane. You'll be able to type into that area. If you want the misspelled words to be underlined as you type them, you will be able to check the JCheckBox that is labeled "Real Time Checking." If you want to underline all of the misspelled words currently in the JTextPane, you can press the JButton with the label "Mark Misspelled Words." To bring up the standard spelling dialog box that presents you with alternatives for misspelled words, you can press the JButton labeled "Get Suggestions." Sure, the cyan is an unnecessary touch, but it made the screen shots look better on a white background.

The class MainFrame will be a JFrame that contains a cyan JTextPane. We can do this in the constructor as follows:


    JTextPane textPane = new JTextPane();
    textPane.setBackground(Color.cyan);
    getContentPane().add(textPane, BorderLayout.CENTER);

Next, check to make sure that the application is running on a Mac. If it is, set up the SpellingToolbar and add it to the top part of the MainFrame. Pass a handle to the textPane into the SpellingToolbar so it knows the text component that it will be spell checking.

Here's the code for MainFrame.java:


import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Color;

public class MainFrame extends JFrame{


  public MainFrame(){
    super("Spell Checking Example");
    JTextPane textPane = new JTextPane();
    textPane.setBackground(Color.cyan);
    getContentPane().add(textPane, BorderLayout.CENTER);
    if (UIManager.getSystemLookAndFeelClassName().endsWith("MacLookAndFeel")){
      getContentPane().add(new SpellingToolbar(textPane), BorderLayout.NORTH);
    }
    setSize(500,450);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public static void main(String[] args){
    new MainFrame();
  }

}

Go ahead and save it. It won't compile yet because we haven't defined the SpellingToolbar class. We'll do that next.

The Shell for the SpellingToolbar

Comment on this articleLet's discuss how this tutorial went for you and the Java on the Mac questions you have.
Post your comments

At this point, we'll add the cosmetic pieces of the SpellingToolbar class to display the JCheckBox and the two JButtons. They don't do anything, but you can compile and run the application and then type away in the JTextPane and click on the buttons to your heart's content. The constructor calls two methods. The first initializes the buttons and the second method adds the buttons to the SpellingToolbar so that they are visible.

Here's the beginning contents of SpellingToolbar.java:


import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JTextPane;

public class SpellingToolbar extends JPanel {

  private JCheckBox realTimeSpellCheckingCheckBox;
  private JButton markMisspelledWordsButton, enterSpellingSessionButton;

  public SpellingToolbar(JTextPane textPane){

    createButtons();
    addButtonsToPanel();

  }

  private void createButtons() {
    markMisspelledWordsButton = new JButton("Mark Misspelled Words");
    realTimeSpellCheckingCheckBox = new JCheckBox("Real Time Checking", false);
    enterSpellingSessionButton = new JButton("Get Suggestions");
  }

  private void addButtonsToPanel() {
    add(markMisspelledWordsButton);
    add(realTimeSpellCheckingCheckBox);
    add(enterSpellingSessionButton);
  }
}

The JTextComponentDriver Class and Checking for Misspelled Words

Our high-level hooks into the spell checking mechanism are provided in the class com.apple.spell.ui.JTextComponentDriver. It contains four methods that we'll use in our application: checkSpelling(), markMisspelledWords(), startRealtimeChecking(), and stopRealtimeChecking(). To perform any of the three tasks we're adding to our application, we'll need to first instantiate a JTextComponentDriver.

We'll also need to pass a handle to the JTextComponent that is being spell-checked. The abstract class javax.swing.text.JTextComponent serves as the base class for all of the Swing text components. In this example, the JTextComponent is actually a JTextPane, but in Java it's best to refer to the text component with the appropriate level of abstraction.

In order to enable the markMisspelledWordsButton, we'll provide an action listener for it. We'll create an inner class called MisspelledWordsMarkerListener that is responsible for calling the markMisspelledWords() method. The changes are highlighted below. Other than the import statements, you'll notice that not a lot of code is required to add this capability to your application.


import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.text.JTextComponent;
import com.apple.spell.ui.JTextComponentDriver;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class SpellingToolbar extends JPanel {

  private JTextComponentDriver driver = new JTextComponentDriver();
  private JTextComponent textComponent;
  private JCheckBox realTimeSpellCheckingCheckBox;
  private JButton markMisspelledWordsButton, enterSpellingSessionButton;

  public SpellingToolbar(JTextPane textPane){
   textComponent = textPane;
   createButtons();
   createActionListeners();
   addButtonsToPanel();
  }

  private void createActionListeners() {
    markMisspelledWordsButton.addActionListener(new MisspelledWordsMarkerListener());
  }

  private void createButtons() {
    markMisspelledWordsButton = new JButton("Mark Misspelled Words");
    realTimeSpellCheckingCheckBox = new JCheckBox("Real Time Checking", false);
    enterSpellingSessionButton = new JButton("Get Suggestions");
  }

  private void addButtonsToPanel() {
    add(markMisspelledWordsButton);
    add(realTimeSpellCheckingCheckBox);
    add(enterSpellingSessionButton);
  }

   class MisspelledWordsMarkerListener implements ActionListener{

    public void actionPerformed(ActionEvent e) {
      driver.markMisspelledWords(textComponent,0,-1);
    }
  }
}

Really, all of the action is in the actionPerformed() method of the MisspelledWordsMarkerListener. When the button labelled "Mark Misspelled Words" is selected, the method markMisspelledWords is invoked on the JTextPane that is locally referred to as textComponent. You can specify which portion of the document is to be spell-checked. In this case, the arguments 0 and -1 indicate that the document should be searched from beginning to end. Save and compile your work. Run your application by running MainFrame. If you're using the terminal, perform these two steps by navigating inside of the directory containing your source files SpellingToolbar.java and MainFrame.java. Type in the command:

javac *.java

Then run the application by entering the command

java MainFrame

Your window should pop open. Type in some sample text with some misspellings. You shouldn't see anything special. Now push the button labeled "Mark Misspelled Words" and the misspelled words that the dictionary knows about should be identified. If this doesn't work, check your installation. In particular, check that the file libspeller.jnilib is in the /usr/lib/java directory. You should get something that looks like this:

Marking Misspelled Words

Pages: 1, 2

Next Pagearrow