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



Previous Page Previous Page (2/9) - Next Page (4/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.3  Word Processor: part III - Colors and images

Important RTF features we will exploit in this section include the ability to use foreground and background colors and insert images into the text. In this example we show how to add these capabilities to our growing RTF word processor application.

Figure 20.3 JTextPane with diverse font styles, foreground colors, and an embedded image.

<<file figure20-3.gif>>

The Code: WordProcessor.java

see \Chapter20\3

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

{

  // Unchanged code from section 20.2

  protected SimpleFilter m_jpgFilter;

  protected SimpleFilter m_gifFilter;

  protected ColorMenu m_foreground;

  protected ColorMenu m_background;

  public WordProcessor() {

    // Unchanged code from section 20.2

    m_chooser = new JFileChooser();

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

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

    m_chooser.setFileFilter(m_rtfFilter);

    m_gifFilter = new SimpleFilter("gif", "GIF images");

    m_jpgFilter = new SimpleFilter("jpg", "JPG images");

    // Unchanged code from section 20.2       

  }

  protected JMenuBar createMenuBar() {

    // Unchanged code from section 20.2

    JMenu mFormat = new JMenu("Format");

    mFormat.setMnemonic('o');

    m_foreground = new ColorMenu("Foreground");

    m_foreground.setColor(m_monitor.getForeground());

    m_foreground.setMnemonic('f');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        MutableAttributeSet attr = new SimpleAttributeSet();

        StyleConstants.setForeground(attr, m_foreground.getColor());

        setAttributeSet(attr);

      }

    };

    m_foreground.addActionListener(lst);

    mFormat.add(m_foreground);

    MenuListener ml = new MenuListener() {

      public void menuSelected(MenuEvent e) {

        int p = m_monitor.getCaretPosition();

        AttributeSet a = m_doc.getCharacterElement(p).

          getAttributes();

        Color c = StyleConstants.getForeground(a);

        m_foreground.setColor(c);

      }

      public void menuDeselected(MenuEvent e) {}

      public void menuCanceled(MenuEvent e) {}

    };

    m_foreground.addMenuListener(ml);

    // Bug Alert! JEditorPane background color

    // doesn't work as of Java 2 FCS.

    m_background = new ColorMenu("Background");

    m_background.setColor(m_monitor.getBackground());

    m_background.setMnemonic('b');

    lst = new ActionListener()  {

      public void actionPerformed(ActionEvent e) {

        MutableAttributeSet attr = new SimpleAttributeSet();

        StyleConstants.setBackground(attr, m_background.getColor());

        setAttributeSet(attr);

      }

    };

    m_background.addActionListener(lst);

    mFormat.add(m_background);

    ml = new MenuListener() {

      public void menuSelected(MenuEvent e) {

        int p = m_monitor.getCaretPosition();

        AttributeSet a = m_doc.getCharacterElement(p).

          getAttributes();

        Color c = StyleConstants.getBackground(a);

        m_background.setColor(c);

      }

      public void menuDeselected(MenuEvent e) {}

      public void menuCanceled(MenuEvent e) {}

    };

    m_background.addMenuListener(ml);

    // Bug Alert! Images do not get saved.

    mFormat.addSeparator();

    item = new JMenuItem("Insert Image"); 

    item.setMnemonic('i');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        m_chooser.addChoosableFileFilter(m_gifFilter);

        m_chooser.addChoosableFileFilter(m_jpgFilter);

        m_chooser.setFileFilter(m_gifFilter);

        m_chooser.removeChoosableFileFilter(m_rtfFilter);

        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();

            ImageIcon icon = new ImageIcon(fChoosen.getPath());

            int w = icon.getIconWidth();

            int h = icon.getIconHeight();

            if (w<=0 || h<=0) {

              JOptionPane.showMessageDialog(WordProcessor.this,

                "Error reading image file\n"+

                fChoosen.getPath(), "Warning",

                JOptionPane.WARNING_MESSAGE);

                return;

            }

            MutableAttributeSet attr = new SimpleAttributeSet();

            StyleConstants.setIcon(attr, icon);

            int p = m_monitor.getCaretPosition();

            try {

              m_doc.insertString(p, " ", attr);

            }

            catch (BadLocationException ex) {}

            // Its ok to do this outside of the event-dispatching

            // thread because the chooser is not visible here.

            m_chooser.addChoosableFileFilter(m_rtfFilter);

            m_chooser.setFileFilter(m_rtfFilter);

            m_chooser.removeChoosableFileFilter(m_gifFilter);

            m_chooser.removeChoosableFileFilter(m_jpgFilter);

          }

        };

        runner.start();

      }

    };

    item.addActionListener(lst);

    mFormat.add(item);

    menuBar.add(mFormat);

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

    return menuBar;

  }

  // Unchanged code from section 20.2

}

// Unchanged code from section 20.2

// Class ColorMenu unchanged from section 12.5

Understanding the Code

Class WordProcessor

Four new instance variables have been added:

SimpleFilter m_jpgFilter: Used for JPEG image selection with JFileChooser (see chapter 14 for more about SimpleFilter).

SimpleFilter m_gifFilter: Used for GIF image selection with JFileChooser.

ColorMenu m_foreground: used to choose the selected text foreground color.

ColorMenu m_background: used to choose the selected text background color.

The ColorMenu class was constructed and discussed in chapter 12, and is used here without modification. This class represents a custom menu component used to select a color from a collection of 64 pre-defined colors. To deploy this component in our application we add a menu titled "Format" with menu items titled "Foreground" and "Background." We also add, after a menu separator, the menu item "Insert Image" (see below).

The ColorMenu m_foreground receives an ActionListener which retrieves the selected color with the getColor() method and then applies it to the selected text by making calls to StyleConstants.setForeground() and setAttributeSet() methods, similar to how we assigned new font attributes in the previous example. In order to maintain consistency we need to update the ColorMenu component prior to displaying it to make the initial color selection consistent with the text foreground at the cursor position. For this purpose we add a MenuListener to the m_foreground component. The menuSelected() method will be called prior to menu selection. Similar to the showAttributes() method discussed above, this code retrieves an AttributeSet instance corresponding to the current caret location and determines the selected foreground color with getForeground(). Then this color is passed to the ColorMenu component for use as the selection.

The m_background ColorMenu works similar to m_foreground, but manages selected text background color. Note that this feature doesn't work with the current RTF API release: it is neither displayed nor saved in the file. The background color menu is added to our word processor for the sake of completeness.

The "Insert Image" menu item receives an ActionListener which uses our JFileChooser to select an image file. If an image file is successfully selected and read, we create a MutableAttributeSet instance and pass our image to it with StyleConstants.setIcon(). Then we insert a dummy single space character with that icon attribute using insertString(). Note that all this occurs in a separate thread to avoid the possibility of clogging the event-dispathing thread.

Running the Code

Open an existing RTF file, select a portion of text and use the custom color menu component to modify it's foreground. Save the RTF file and open it in another RTF-aware application to verify that your changes have been saved correctly. Try using the "Insert Image" menu to bring up a file chooser and select an image for insertion.

Bug Alert! Unfortunately embedded images are neither saved to file or read from an existing RTF document. We hope that this problem/limitation will be fixed soon in a future release.



[ 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