Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 20. (Advanced topics) Constructing a Word Processor. Easy for reading, Click here!

Custom Search
Swing Chapter 20. (Advanced topics) Constructing a Word Processor. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/9 



Next Page (2/9) Next Page

Chapter 20. Constructing a Word Processor

Subpages: 1. Word Processor: part I - Introducing RTF
2. Word Processor: part II - Managing fonts
3. Word Processor: part III - Colors and images
4. Word Processor: part IV - Working with styles
5. Word Processor: part V - Clipboard and undo/redo
6. Word Processor: part VI - Advanced font mangement
7. Word Processor: part VII - Paragraph formatting
8. Word Processor: part VIII - Find and replace
9. Word Processor: part IX - Spell checker [using JDBC and SQL]

In this chapter:

  •          Word Processor: part I - Introducing RTF
  •          Word Processor: part II - Managing fonts
  •          Word Processor: part III - Colors and images
  •          Word Processor: part IV - Working with styles
  •          Word Processor: part V - Clipboard and undo/redo
  •          Word Processor: part VI - Advanced font mangement
  •          Word Processor: part VII - Paragraph formatting
  •          Word Processor: part VIII - Find and replace
  •          Word Processor: part IX - Spell checker [using JDBC and SQL]

This chapter is devoted to the construction of a fully-functional RTF word processor application. Though Swing's HTML and RTF capabilities are very powerful, they are not yet complete. RTF support is further along than HTML, and this is why we chose to design our word processor for use with RTF documents. The examples in this chapter demonstrate practical applications of many of the topics covered in chapter 19. The main focus throughout is working with styled text documents, and the techniques discussed here can be applied to any styled text editor.

Note: When running the examples in this chapter, do not be surprised when you see a series of 'unknown keyword' warnings or exception problems with various Views. You will also see the following message displayed to emphasize the fact that RTF support is still in the works: "Problems encountered: Note that RTF support is still under development."

20.1  Word Processor: part I - Introducing RTF

This basic example uses the capabilities of JTextPane and RTFEditorKit to display and edit RTF documents. It demonstrates very basic word processor functionality, opening and saving an RTF file, and serves as the foundation for our word processor application to be expanded upon throughout this chapter.

Note: In this series of examples our goal is to demonstrate the most significant available features of advanced text editing in Swing (even if they do not all currently work properly). To avoid losing focus of this goal we intentionally omit several typical word processor features such as an MDI interface, status bar, and prompts to save the current file before closing.

Figure 20.1 JTextPane displaying an RTF document.

<<file figure20-1.gif>>

The Code: WordProcessor.java

see \Chapter20\1

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.rtf.*;
public class WordProcessor extends JFrame
{

  protected JTextPane m_monitor;

  protected StyleContext m_context;

  protected DefaultStyledDocument m_doc;

  protected RTFEditorKit m_kit;

  protected JFileChooser m_chooser;

  protected SimpleFilter m_rtfFilter;

  protected JToolBar m_toolBar;

  public WordProcessor() {

    super("RTF Word Processor");

    setSize(600, 400);

    // Make sure we install the editor kit before creating

    // the initial document.

    m_monitor = new JTextPane();

    m_kit = new RTFEditorKit();

    m_monitor.setEditorKit(m_kit);

    m_context = new StyleContext();

    m_doc = new DefaultStyledDocument(m_context);

    m_monitor.setDocument(m_doc);

    JScrollPane ps = new JScrollPane(m_monitor);

    getContentPane().add(ps, BorderLayout.CENTER);

    JMenuBar menuBar = createMenuBar();

    setJMenuBar(menuBar);

    m_chooser = new JFileChooser();

    m_chooser.setCurrentDirectory(new File("."));

    m_rtfFilter = new SimpleFilter("rtf", "RTF Documents");

    m_chooser.setFileFilter(m_rtfFilter);

    WindowListener wndCloser = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    };

    addWindowListener(wndCloser);

    setVisible(true);

  }

  protected JMenuBar createMenuBar() {

    JMenuBar menuBar = new JMenuBar();

    JMenu mFile = new JMenu("File");

    mFile.setMnemonic('f');

    ImageIcon iconNew = new ImageIcon("file_new.gif");

    Action actionNew = new AbstractAction("New", iconNew) {

      public void actionPerformed(ActionEvent e) {

        m_doc = new DefaultStyledDocument(m_context);

        m_monitor.setDocument(m_doc);

      }

    };

    JMenuItem item =  mFile.add(actionNew); 

    item.setMnemonic('n');

    ImageIcon iconOpen = new ImageIcon("file_open.gif");

    Action actionOpen = new AbstractAction("Open...", iconOpen) {

      public void actionPerformed(ActionEvent e) {

        WordProcessor.this.setCursor(

          Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        Thread runner = new Thread() {

          public void run() {

            if (m_chooser.showOpenDialog(WordProcessor.this) !=

             JFileChooser.APPROVE_OPTION)

              return;

            WordProcessor.this.repaint();

            File fChoosen = m_chooser.getSelectedFile();

            // Recall that text component read/write operations are

            // thread safe. Its ok to do this in a separate thread.

            try {

              InputStream in = new FileInputStream(fChoosen);

              m_doc = new DefaultStyledDocument(m_context);

              m_kit.read(in, m_doc, 0);

              m_monitor.setDocument(m_doc);

              in.close();

            }

            catch (Exception ex) {

              ex.printStackTrace();

            }

            WordProcessor.this.setCursor(Cursor.getPredefinedCursor(

              Cursor.DEFAULT_CURSOR));

          }

        };

        runner.start();

      }

    };

    item =  mFile.add(actionOpen); 

    item.setMnemonic('o');

    ImageIcon iconSave = new ImageIcon("file_save.gif");

    Action actionSave = new AbstractAction("Save...", iconSave) {

      public void actionPerformed(ActionEvent e) {

        WordProcessor.this.setCursor(

          Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        Thread runner = new Thread() {

          public void run() {

            if (m_chooser.showSaveDialog(WordProcessor.this) !=

             JFileChooser.APPROVE_OPTION)

              return;

            WordProcessor.this.repaint();

            File fChoosen = m_chooser.getSelectedFile();

            // Recall that text component read/write operations are

            // thread safe. Its ok to do this in a separate thread.

            try {

              OutputStream out = new FileOutputStream(fChoosen);

              m_kit.write(out, m_doc, 0, m_doc.getLength());

              out.close();

            }

            catch (Exception ex) {

              ex.printStackTrace();

            }

            // Make sure chooser is updated to reflect new file

            m_chooser.rescanCurrentDirectory();

            WordProcessor.this.setCursor(Cursor.getPredefinedCursor(

              Cursor.DEFAULT_CURSOR));

          }

        };

        runner.start();

      }

    };

    item = mFile.add(actionSave); 

    item.setMnemonic('s');

    mFile.addSeparator();

    Action actionExit = new AbstractAction("Exit") {

      public void actionPerformed(ActionEvent e) {

        System.exit(0);

      }

    };

    item =  mFile.add(actionExit); 

    item.setMnemonic('x');

    menuBar.add(mFile);

    m_toolBar = new JToolBar();

    JButton bNew = new SmallButton(actionNew, "New document");

    m_toolBar.add(bNew);

    JButton bOpen = new SmallButton(actionOpen, "Open RTF document");

    m_toolBar.add(bOpen);

    JButton bSave = new SmallButton(actionSave, "Save RTF document");

    m_toolBar.add(bSave);

    getContentPane().add(m_toolBar, BorderLayout.NORTH);

    return menuBar;

  }

  public static void main(String argv[]) {

    new WordProcessor();

  }

}

// Class SmallButton unchanged from section 12.4

// Class SimpleFilter unchanged from section 14.1.9

Understanding the Code

Class WordProcessor

This class extends JFrame to provide the supporting frame for this example. Several instance variables are declared:

JTextPane m_monitor: text component.

StyleContext m_context: a group of styles and their associated resources for the documents in this example.

DefaultStyledDocument m_doc: current document model.

RTFEditorKit m_kit: editor kit that knows how to read/write RTF documents.

JFileChooser m_chooser: file chooser used to load and save RTF files.

SimpleFilter m_rtfFilter: file filter for ".rtf" files.

JToolBar m_toolBar: toolbar containing open, save, and new document buttons.

The WordProcessor constructor first instantiates our JTextPane and RTFEditorKit, and assigns the editor kit to the text pane (it is important that this is done before any documents are created). Next our StyleContext is instantiated and we build our DefaultStyledDocument with it. The DefaultStyledDocument is then set as our text pane's current document.

The createMenuBar() method creates a menu bar with a single menu titled "File." Menu items "New," "Open," "Save," and "Exit" are added to the menu. The first three items are duplicated in the toolbar. This code is very similar to the code used in the examples of chapter 12. The important difference is that we use InputStreams and OutputStreams rather than Readers and Writers. The reason for this is that RTF uses 1-byte encoding which is incompatible with the 2-byte encoding used by readers and writers.

Warning: An attempt to invoke read() will throw an exception when JTextPane is using an RTFEditorKit.

Running the Code

Use menu or toolbar buttons to open an RTF file (a sample RTF file is provided in the \swing\Chapter20 directory). Save the RTF file and open it in another RTF-aware application (such as Microsoft Word) to verify compatibility.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy