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: 5/9 



Previous Page Previous Page (4/9) - Next Page (6/9) Next Page
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]

20.5  Word Processor: part V - Clipboard and Undo/Redo

Clipboard and undo/redo operations have become common and necessary components of all modern text editing environments. We have discussed these features in chapters 11 and 19, and in this section we show how to integrate them into our RTF word processor.

Figure 20.5 RTF word processor with undo/redo and clipboard functionality.

<<file figure20-5.gif>>

The Code: WordProcessor.java

see \Chapter20\5

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.*;

import javax.swing.undo.*;

public class WordProcessor extends JFrame

{    

  // Unchanged code from section 20.4

  protected UndoManager m_undo = new UndoManager();

  protected Action m_undoAction;

  protected Action m_redoAction;

  public WordProcessor() {

    // Unchanged code from section 20.4

    showAttributes(0);

    showStyles();

    m_doc.addUndoableEditListener(new Undoer());

    setVisible(true);

  }

  protected JMenuBar createMenuBar() {

    // The following line is added to the end of the

    // actionNew and actionOpen actionPerformed() methods:

    //

    //   m_doc.addUndoableEditListener(new Undoer());

    //

    // (see source code; these methods are not shown here

    //  to conserve space)

    // Unchanged code from section 20.4

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

    m_toolBar.add(bSave);

    JMenu mEdit = new JMenu("Edit");

    mEdit.setMnemonic('e');

    Action action = new AbstractAction("Copy",

     new ImageIcon("edit_copy.gif"))

    {

      public void actionPerformed(ActionEvent e) {

        m_monitor.copy();

      }

    };

    item = mEdit.add(action); 

    item.setMnemonic('c');

    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,

      KeyEvent.CTRL_MASK));

    action = new AbstractAction("Cut",

     new ImageIcon("edit_cut.gif"))

    {

      public void actionPerformed(ActionEvent e) {

        m_monitor.cut();

      }

    };

    item = mEdit.add(action); 

    item.setMnemonic('t');

    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,

      KeyEvent.CTRL_MASK));

    action = new AbstractAction("Paste",

     new ImageIcon("edit_paste.gif"))

    {

      public void actionPerformed(ActionEvent e) {

        m_monitor.paste();

      }

    };

    item = mEdit.add(action); 

    item.setMnemonic('p');

    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,

      KeyEvent.CTRL_MASK));

    mEdit.addSeparator();

    m_undoAction = new AbstractAction("Undo",

     new ImageIcon("edit_undo.gif"))

    {

      public void actionPerformed(ActionEvent e) {

        try {

          m_undo.undo();

        }

        catch (CannotUndoException ex) {

          System.err.println("Unable to undo: " + ex);

        }

        updateUndo();

      }

    };

    item = mEdit.add(m_undoAction); 

    item.setMnemonic('u');

    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,

      KeyEvent.CTRL_MASK));

    m_redoAction = new AbstractAction("Redo",

     new ImageIcon("edit_redo.gif"))

    {

      public void actionPerformed(ActionEvent e) {

        try {

          m_undo.redo();

        }

        catch (CannotRedoException ex) {

          System.err.println("Unable to redo: " + ex);

        }

        updateUndo();

      }

    };

    item =  mEdit.add(m_redoAction); 

    item.setMnemonic('r');

    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y,

      KeyEvent.CTRL_MASK));

    menuBar.add(mEdit);

    GraphicsEnvironment ge = GraphicsEnvironment.

      getLocalGraphicsEnvironment();

    String[] fontNames = ge.getAvailableFontFamilyNames();

    // Unchanged code from section 20.4

    return menuBar;

  }

  // Unchanged code from section 20.4

  protected void updateUndo() {

    if(m_undo.canUndo()) {

      m_undoAction.setEnabled(true);

      m_undoAction.putValue(Action.NAME,

      m_undo.getUndoPresentationName());

    }

    else {

      m_undoAction.setEnabled(false);

      m_undoAction.putValue(Action.NAME, "Undo");

    }

    if(m_undo.canRedo()) {

      m_redoAction.setEnabled(true);

      m_redoAction.putValue(Action.NAME,

      m_undo.getRedoPresentationName());

    }

    else {

      m_redoAction.setEnabled(false);

      m_redoAction.putValue(Action.NAME, "Redo");

    }

  }

  public static void main(String argv[]) {

    new WordProcessor();

  }

  class Undoer implements UndoableEditListener

  {

    public Undoer() {

      m_undo.die();

      updateUndo();

    }

    public void undoableEditHappened(UndoableEditEvent e) {

      UndoableEdit edit = e.getEdit();

      m_undo.addEdit(e.getEdit());

      updateUndo();

    }

  }

}

// Unchanged code from section 20.4

Understanding the Code

Class WordProcessor

We now import the javax.swing.undo package and add three new instance variables:

UndoManager m_undo: used to manage undo/redo operations.

Action m_undoAction: used for a menu item/action to perform undo operations.

Action m_redoAction: used for a menu item/action to perform redo operations.

Note that a new Undoer instance (see below) is now added as an UndoableEditListener to all newly created or loaded documents.

The createMenuBar() method now creates a menu titled "Edit" (which traditionally follows the "File" menu) containing menu items titled "Copy," "Cut," "Paste," "Undo," and "Redo." The first three items merely trigger calls to the copy(), cut(), and paste() methods of our m_monitor text pane. These methods perform clipboard operations using plain text without any attributes. They are available when the editor has the current focus and the appropriate keyboard accelerator is pressed. These items are added to our "Edit" menu to provide a convenient and informative interface.

The "Undo" menu item is created from an AbstractAction whose actionPerformed() method first invokes undo() on the UndoManager, and then invokes our custom updateUndo() method to update our undo/redo menu items appropriately. Similarly, the "Redo" menu item is created from an AbstractAction which invokes redo() on the UndoManager, and then calls our updateUndo() method.

The updateUndo() method enables or disables the undo and redo menu items, and updates their names according to the operation which can be undone/redone (if any). If the UndoManager's canUndo() method returns true, the m_undoAction is enabled and its name is set to the string returned by getUndoPresentationName(). Otherwise it is disabled and its name is set to "Undo." The "Redo" menu item is handled similarly.

Class WordProcessor.Undoer

This inner class implements the UndoableEditListener interface to receive notifications about undoable operations. The undoableEditHappened() method receives UndoableEditEvents, retrieves their encapsulated UndoableEdit instances, and passes them to the UndoManager. Our updateUndo() method is also invoked to update the undo/redo menu items appropriately.

Running the Code

Open an existing RTF file and verify that copy, cut, and paste clipboard operations transfer plain text successfully. Make some changes to the textual content or styles and note that the title of the "Undo" menu item is updated. Select this menu item, or press its keyboard accelerator (Ctrl-Z) to undo a series of changes. This will enable the "Redo" menu item. Use this menu item or press its keyboard accelerator (Ctrl-Y) to redo a series of changes.



[ 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