KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > text > StyledEditorKit


1 /*
2  * @(#)StyledEditorKit.java 1.45 04/02/04
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package javax.swing.text;
8
9 import java.io.*;
10 import java.awt.*;
11 import java.awt.event.ActionEvent JavaDoc;
12 import java.beans.PropertyChangeEvent JavaDoc;
13 import java.beans.PropertyChangeListener JavaDoc;
14 import javax.swing.event.*;
15 import javax.swing.Action JavaDoc;
16 import javax.swing.JEditorPane JavaDoc;
17 import javax.swing.KeyStroke JavaDoc;
18 import javax.swing.UIManager JavaDoc;
19
20 /**
21  * This is the set of things needed by a text component
22  * to be a reasonably functioning editor for some <em>type</em>
23  * of text document. This implementation provides a default
24  * implementation which treats text as styled text and
25  * provides a minimal set of actions for editing styled text.
26  *
27  * @author Timothy Prinzing
28  * @version 1.45 02/04/04
29  */

30 public class StyledEditorKit extends DefaultEditorKit JavaDoc {
31
32     /**
33      * Creates a new EditorKit used for styled documents.
34      */

35     public StyledEditorKit() {
36         createInputAttributeUpdated();
37         createInputAttributes();
38     }
39
40     /**
41      * Gets the input attributes for the pane. When
42      * the caret moves and there is no selection, the
43      * input attributes are automatically mutated to
44      * reflect the character attributes of the current
45      * caret location. The styled editing actions
46      * use the input attributes to carry out their
47      * actions.
48      *
49      * @return the attribute set
50      */

51     public MutableAttributeSet JavaDoc getInputAttributes() {
52     return inputAttributes;
53     }
54
55     /**
56      * Fetches the element representing the current
57      * run of character attributes for the caret.
58      *
59      * @return the element
60      */

61     public Element JavaDoc getCharacterAttributeRun() {
62     return currentRun;
63     }
64
65     // --- EditorKit methods ---------------------------
66

67     /**
68      * Fetches the command list for the editor. This is
69      * the list of commands supported by the superclass
70      * augmented by the collection of commands defined
71      * locally for style operations.
72      *
73      * @return the command list
74      */

75     public Action JavaDoc[] getActions() {
76     return TextAction.augmentList(super.getActions(), this.defaultActions);
77     }
78    
79     /**
80      * Creates an uninitialized text storage model
81      * that is appropriate for this type of editor.
82      *
83      * @return the model
84      */

85     public Document JavaDoc createDefaultDocument() {
86     return new DefaultStyledDocument JavaDoc();
87     }
88
89     /**
90      * Called when the kit is being installed into
91      * a JEditorPane.
92      *
93      * @param c the JEditorPane
94      */

95     public void install(JEditorPane JavaDoc c) {
96     c.addCaretListener(inputAttributeUpdater);
97     c.addPropertyChangeListener(inputAttributeUpdater);
98     Caret JavaDoc caret = c.getCaret();
99     if (caret != null) {
100         inputAttributeUpdater.updateInputAttributes
101                           (caret.getDot(), caret.getMark(), c);
102     }
103     }
104
105     /**
106      * Called when the kit is being removed from the
107      * JEditorPane. This is used to unregister any
108      * listeners that were attached.
109      *
110      * @param c the JEditorPane
111      */

112     public void deinstall(JEditorPane JavaDoc c) {
113     c.removeCaretListener(inputAttributeUpdater);
114     c.removePropertyChangeListener(inputAttributeUpdater);
115
116     // remove references to current document so it can be collected.
117
currentRun = null;
118     currentParagraph = null;
119     }
120
121    /**
122      * Fetches a factory that is suitable for producing
123      * views of any models that are produced by this
124      * kit. This is implemented to return View implementations
125      * for the following kinds of elements:
126      * <ul>
127      * <li>AbstractDocument.ContentElementName
128      * <li>AbstractDocument.ParagraphElementName
129      * <li>AbstractDocument.SectionElementName
130      * <li>StyleConstants.ComponentElementName
131      * <li>StyleConstants.IconElementName
132      * </ul>
133      *
134      * @return the factory
135      */

136     public ViewFactory JavaDoc getViewFactory() {
137     return defaultFactory;
138     }
139
140     /**
141      * Creates a copy of the editor kit.
142      *
143      * @return the copy
144      */

145     public Object JavaDoc clone() {
146     StyledEditorKit JavaDoc o = (StyledEditorKit JavaDoc)super.clone();
147         o.currentRun = o.currentParagraph = null;
148         o.createInputAttributeUpdated();
149         o.createInputAttributes();
150     return o;
151     }
152
153     /**
154      * Creates the AttributeSet used for the selection.
155      */

156     private void createInputAttributes() {
157         inputAttributes = new SimpleAttributeSet JavaDoc() {
158             public AttributeSet JavaDoc getResolveParent() {
159                 return (currentParagraph != null) ?
160                            currentParagraph.getAttributes() : null;
161             }
162
163             public Object JavaDoc clone() {
164                 return new SimpleAttributeSet JavaDoc(this);
165             }
166         };
167     }
168
169     /**
170      * Creates a new <code>AttributeTracker</code>.
171      */

172     private void createInputAttributeUpdated() {
173         inputAttributeUpdater = new AttributeTracker();
174     }
175
176
177     private static final ViewFactory JavaDoc defaultFactory = new StyledViewFactory();
178
179     Element JavaDoc currentRun;
180     Element JavaDoc currentParagraph;
181
182     /**
183      * This is the set of attributes used to store the
184      * input attributes.
185      */

186     MutableAttributeSet JavaDoc inputAttributes;
187
188     /**
189      * This listener will be attached to the caret of
190      * the text component that the EditorKit gets installed
191      * into. This should keep the input attributes updated
192      * for use by the styled actions.
193      */

194     private AttributeTracker inputAttributeUpdater;
195
196     /**
197      * Tracks caret movement and keeps the input attributes set
198      * to reflect the current set of attribute definitions at the
199      * caret position.
200      * <p>This implements PropertyChangeListener to update the
201      * input attributes when the Document changes, as if the Document
202      * changes the attributes will almost certainly change.
203      */

204     class AttributeTracker implements CaretListener, PropertyChangeListener JavaDoc, Serializable {
205
206     /**
207      * Updates the attributes. <code>dot</code> and <code>mark</code>
208      * mark give the positions of the selection in <code>c</code>.
209      */

210     void updateInputAttributes(int dot, int mark, JTextComponent JavaDoc c) {
211         // EditorKit might not have installed the StyledDocument yet.
212
Document JavaDoc aDoc = c.getDocument();
213         if (!(aDoc instanceof StyledDocument JavaDoc)) {
214         return ;
215         }
216         int start = Math.min(dot, mark);
217         // record current character attributes.
218
StyledDocument JavaDoc doc = (StyledDocument JavaDoc)aDoc;
219         // If nothing is selected, get the attributes from the character
220
// before the start of the selection, otherwise get the attributes
221
// from the character element at the start of the selection.
222
Element JavaDoc run;
223         currentParagraph = doc.getParagraphElement(start);
224         if (currentParagraph.getStartOffset() == start || dot != mark) {
225         // Get the attributes from the character at the selection
226
// if in a different paragrah!
227
run = doc.getCharacterElement(start);
228         }
229         else {
230         run = doc.getCharacterElement(Math.max(start-1, 0));
231         }
232         if (run != currentRun) {
233             /*
234              * PENDING(prinz) All attributes that represent a single
235              * glyph position and can't be inserted into should be
236              * removed from the input attributes... this requires
237              * mixing in an interface to indicate that condition.
238              * When we can add things again this logic needs to be
239              * improved!!
240              */

241         currentRun = run;
242         createInputAttributes(currentRun, getInputAttributes());
243         }
244     }
245
246         public void propertyChange(PropertyChangeEvent JavaDoc evt) {
247         Object JavaDoc newValue = evt.getNewValue();
248         Object JavaDoc source = evt.getSource();
249
250         if ((source instanceof JTextComponent JavaDoc) &&
251         (newValue instanceof Document JavaDoc)) {
252         // New document will have changed selection to 0,0.
253
updateInputAttributes(0, 0, (JTextComponent JavaDoc)source);
254         }
255     }
256
257     public void caretUpdate(CaretEvent e) {
258         updateInputAttributes(e.getDot(), e.getMark(),
259                   (JTextComponent JavaDoc)e.getSource());
260     }
261     }
262
263     /**
264      * Copies the key/values in <code>element</code>s AttributeSet into
265      * <code>set</code>. This does not copy component, icon, or element
266      * names attributes. Subclasses may wish to refine what is and what
267      * isn't copied here. But be sure to first remove all the attributes that
268      * are in <code>set</code>.<p>
269      * This is called anytime the caret moves over a different location.
270      *
271      */

272     protected void createInputAttributes(Element JavaDoc element,
273                      MutableAttributeSet JavaDoc set) {
274         if (element.getAttributes().getAttributeCount() > 0
275             || element.getEndOffset() - element.getStartOffset() > 1
276             || element.getEndOffset() < element.getDocument().getLength()) {
277         set.removeAttributes(set);
278         set.addAttributes(element.getAttributes());
279         set.removeAttribute(StyleConstants.ComponentAttribute);
280         set.removeAttribute(StyleConstants.IconAttribute);
281         set.removeAttribute(AbstractDocument.ElementNameAttribute);
282         set.removeAttribute(StyleConstants.ComposedTextAttribute);
283     }
284     }
285
286     // ---- default ViewFactory implementation ---------------------
287

288     static class StyledViewFactory implements ViewFactory JavaDoc {
289
290         public View JavaDoc create(Element JavaDoc elem) {
291         String JavaDoc kind = elem.getName();
292         if (kind != null) {
293         if (kind.equals(AbstractDocument.ContentElementName)) {
294                     return new LabelView JavaDoc(elem);
295         } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
296             return new ParagraphView JavaDoc(elem);
297         } else if (kind.equals(AbstractDocument.SectionElementName)) {
298             return new BoxView JavaDoc(elem, View.Y_AXIS);
299         } else if (kind.equals(StyleConstants.ComponentElementName)) {
300             return new ComponentView JavaDoc(elem);
301         } else if (kind.equals(StyleConstants.IconElementName)) {
302             return new IconView JavaDoc(elem);
303         }
304         }
305     
306         // default to text display
307
return new LabelView JavaDoc(elem);
308     }
309
310     }
311
312     // --- Action implementations ---------------------------------
313

314     private static final Action JavaDoc[] defaultActions = {
315     new FontFamilyAction("font-family-SansSerif", "SansSerif"),
316     new FontFamilyAction("font-family-Monospaced", "Monospaced"),
317     new FontFamilyAction("font-family-Serif", "Serif"),
318     new FontSizeAction("font-size-8", 8),
319     new FontSizeAction("font-size-10", 10),
320     new FontSizeAction("font-size-12", 12),
321     new FontSizeAction("font-size-14", 14),
322     new FontSizeAction("font-size-16", 16),
323     new FontSizeAction("font-size-18", 18),
324     new FontSizeAction("font-size-24", 24),
325     new FontSizeAction("font-size-36", 36),
326     new FontSizeAction("font-size-48", 48),
327     new AlignmentAction("left-justify", StyleConstants.ALIGN_LEFT),
328     new AlignmentAction("center-justify", StyleConstants.ALIGN_CENTER),
329     new AlignmentAction("right-justify", StyleConstants.ALIGN_RIGHT),
330     new BoldAction(),
331     new ItalicAction(),
332         new StyledInsertBreakAction(),
333     new UnderlineAction()
334     };
335
336     /**
337      * An action that assumes it's being fired on a JEditorPane
338      * with a StyledEditorKit (or subclass) installed. This has
339      * some convenience methods for causing character or paragraph
340      * level attribute changes. The convenience methods will
341      * throw an IllegalArgumentException if the assumption of
342      * a StyledDocument, a JEditorPane, or a StyledEditorKit
343      * fail to be true.
344      * <p>
345      * The component that gets acted upon by the action
346      * will be the source of the ActionEvent if the source
347      * can be narrowed to a JEditorPane type. If the source
348      * can't be narrowed, the most recently focused text
349      * component is changed. If neither of these are the
350      * case, the action cannot be performed.
351      * <p>
352      * <strong>Warning:</strong>
353      * Serialized objects of this class will not be compatible with
354      * future Swing releases. The current serialization support is
355      * appropriate for short term storage or RMI between applications running
356      * the same version of Swing. As of 1.4, support for long term storage
357      * of all JavaBeans<sup><font size="-2">TM</font></sup>
358      * has been added to the <code>java.beans</code> package.
359      * Please see {@link java.beans.XMLEncoder}.
360      */

361     public abstract static class StyledTextAction extends TextAction JavaDoc {
362
363         /**
364          * Creates a new StyledTextAction from a string action name.
365          *
366          * @param nm the name of the action
367          */

368         public StyledTextAction(String JavaDoc nm) {
369         super(nm);
370     }
371
372         /**
373          * Gets the target editor for an action.
374          *
375          * @param e the action event
376          * @return the editor
377          */

378         protected final JEditorPane JavaDoc getEditor(ActionEvent JavaDoc e) {
379         JTextComponent JavaDoc tcomp = getTextComponent(e);
380         if (tcomp instanceof JEditorPane JavaDoc) {
381         return (JEditorPane JavaDoc) tcomp;
382         }
383         return null;
384     }
385
386         /**
387          * Gets the document associated with an editor pane.
388          *
389          * @param e the editor
390          * @return the document
391          * @exception IllegalArgumentException for the wrong document type
392          */

393         protected final StyledDocument JavaDoc getStyledDocument(JEditorPane JavaDoc e) {
394         Document JavaDoc d = e.getDocument();
395         if (d instanceof StyledDocument JavaDoc) {
396         return (StyledDocument JavaDoc) d;
397         }
398         throw new IllegalArgumentException JavaDoc("document must be StyledDocument");
399     }
400
401         /**
402          * Gets the editor kit associated with an editor pane.
403          *
404          * @param e the editor pane
405          * @return the kit
406          * @exception IllegalArgumentException for the wrong document type
407          */

408         protected final StyledEditorKit JavaDoc getStyledEditorKit(JEditorPane JavaDoc e) {
409         EditorKit JavaDoc k = e.getEditorKit();
410         if (k instanceof StyledEditorKit JavaDoc) {
411         return (StyledEditorKit JavaDoc) k;
412         }
413         throw new IllegalArgumentException JavaDoc("EditorKit must be StyledEditorKit");
414     }
415
416     /**
417      * Applies the given attributes to character
418      * content. If there is a selection, the attributes
419      * are applied to the selection range. If there
420      * is no selection, the attributes are applied to
421      * the input attribute set which defines the attributes
422      * for any new text that gets inserted.
423      *
424          * @param editor the editor
425      * @param attr the attributes
426      * @param replace if true, then replace the existing attributes first
427      */

428         protected final void setCharacterAttributes(JEditorPane JavaDoc editor,
429                           AttributeSet JavaDoc attr, boolean replace) {
430         int p0 = editor.getSelectionStart();
431         int p1 = editor.getSelectionEnd();
432         if (p0 != p1) {
433         StyledDocument JavaDoc doc = getStyledDocument(editor);
434         doc.setCharacterAttributes(p0, p1 - p0, attr, replace);
435         }
436         StyledEditorKit JavaDoc k = getStyledEditorKit(editor);
437         MutableAttributeSet JavaDoc inputAttributes = k.getInputAttributes();
438         if (replace) {
439         inputAttributes.removeAttributes(inputAttributes);
440         }
441         inputAttributes.addAttributes(attr);
442     }
443
444     /**
445      * Applies the given attributes to paragraphs. If
446      * there is a selection, the attributes are applied
447      * to the paragraphs that intersect the selection.
448      * if there is no selection, the attributes are applied
449      * to the paragraph at the current caret position.
450      *
451          * @param editor the editor
452      * @param attr the attributes
453      * @param replace if true, replace the existing attributes first
454      */

455         protected final void setParagraphAttributes(JEditorPane JavaDoc editor,
456                        AttributeSet JavaDoc attr, boolean replace) {
457         int p0 = editor.getSelectionStart();
458         int p1 = editor.getSelectionEnd();
459         StyledDocument JavaDoc doc = getStyledDocument(editor);
460         doc.setParagraphAttributes(p0, p1 - p0, attr, replace);
461     }
462
463     }
464
465     /**
466      * An action to set the font family in the associated
467      * JEditorPane. This will use the family specified as
468      * the command string on the ActionEvent if there is one,
469      * otherwise the family that was initialized with will be used.
470      * <p>
471      * <strong>Warning:</strong>
472      * Serialized objects of this class will not be compatible with
473      * future Swing releases. The current serialization support is
474      * appropriate for short term storage or RMI between applications running
475      * the same version of Swing. As of 1.4, support for long term storage
476      * of all JavaBeans<sup><font size="-2">TM</font></sup>
477      * has been added to the <code>java.beans</code> package.
478      * Please see {@link java.beans.XMLEncoder}.
479      */

480     public static class FontFamilyAction extends StyledTextAction {
481
482         /**
483          * Creates a new FontFamilyAction.
484          *
485          * @param nm the action name
486          * @param family the font family
487          */

488     public FontFamilyAction(String JavaDoc nm, String JavaDoc family) {
489         super(nm);
490         this.family = family;
491     }
492
493         /**
494          * Sets the font family.
495          *
496          * @param e the event
497          */

498         public void actionPerformed(ActionEvent JavaDoc e) {
499         JEditorPane JavaDoc editor = getEditor(e);
500         if (editor != null) {
501         String JavaDoc family = this.family;
502         if ((e != null) && (e.getSource() == editor)) {
503             String JavaDoc s = e.getActionCommand();
504             if (s != null) {
505             family = s;
506             }
507         }
508         if (family != null) {
509             MutableAttributeSet JavaDoc attr = new SimpleAttributeSet JavaDoc();
510             StyleConstants.setFontFamily(attr, family);
511             setCharacterAttributes(editor, attr, false);
512         } else {
513             UIManager.getLookAndFeel().provideErrorFeedback(editor);
514         }
515         }
516     }
517
518     private String JavaDoc family;
519     }
520
521     /**
522      * An action to set the font size in the associated
523      * JEditorPane. This will use the size specified as
524      * the command string on the ActionEvent if there is one,
525      * otherwise the size that was initialized with will be used.
526      * <p>
527      * <strong>Warning:</strong>
528      * Serialized objects of this class will not be compatible with
529      * future Swing releases. The current serialization support is
530      * appropriate for short term storage or RMI between applications running
531      * the same version of Swing. As of 1.4, support for long term storage
532      * of all JavaBeans<sup><font size="-2">TM</font></sup>
533      * has been added to the <code>java.beans</code> package.
534      * Please see {@link java.beans.XMLEncoder}.
535      */

536     public static class FontSizeAction extends StyledTextAction {
537
538         /**
539          * Creates a new FontSizeAction.
540          *
541          * @param nm the action name
542          * @param size the font size
543          */

544     public FontSizeAction(String JavaDoc nm, int size) {
545         super(nm);
546         this.size = size;
547     }
548
549         /**
550          * Sets the font size.
551          *
552          * @param e the action event
553          */

554         public void actionPerformed(ActionEvent JavaDoc e) {
555         JEditorPane JavaDoc editor = getEditor(e);
556         if (editor != null) {
557         int size = this.size;
558         if ((e != null) && (e.getSource() == editor)) {
559             String JavaDoc s = e.getActionCommand();
560             try {
561             size = Integer.parseInt(s, 10);
562             } catch (NumberFormatException JavaDoc nfe) {
563             }
564         }
565         if (size != 0) {
566             MutableAttributeSet JavaDoc attr = new SimpleAttributeSet JavaDoc();
567             StyleConstants.setFontSize(attr, size);
568             setCharacterAttributes(editor, attr, false);
569         } else {
570             UIManager.getLookAndFeel().provideErrorFeedback(editor);
571         }
572         }
573     }
574
575     private int size;
576     }
577
578     /**
579      * An action to set foreground color. This sets the
580      * <code>StyleConstants.Foreground</code> attribute for the
581      * currently selected range of the target JEditorPane.
582      * This is done by calling
583      * <code>StyledDocument.setCharacterAttributes</code>
584      * on the styled document associated with the target
585      * JEditorPane.
586      * <p>
587      * If the target text component is specified as the
588      * source of the ActionEvent and there is a command string,
589      * the command string will be interpreted as the foreground
590      * color. It will be interpreted by called
591      * <code>Color.decode</code>, and should therefore be
592      * legal input for that method.
593      * <p>
594      * <strong>Warning:</strong>
595      * Serialized objects of this class will not be compatible with
596      * future Swing releases. The current serialization support is
597      * appropriate for short term storage or RMI between applications running
598      * the same version of Swing. As of 1.4, support for long term storage
599      * of all JavaBeans<sup><font size="-2">TM</font></sup>
600      * has been added to the <code>java.beans</code> package.
601      * Please see {@link java.beans.XMLEncoder}.
602      */

603     public static class ForegroundAction extends StyledTextAction {
604
605         /**
606          * Creates a new ForegroundAction.
607          *
608          * @param nm the action name
609          * @param fg the foreground color
610          */

611     public ForegroundAction(String JavaDoc nm, Color fg) {
612         super(nm);
613         this.fg = fg;
614     }
615
616         /**
617          * Sets the foreground color.
618          *
619          * @param e the action event
620          */

621         public void actionPerformed(ActionEvent JavaDoc e) {
622         JEditorPane JavaDoc editor = getEditor(e);
623         if (editor != null) {
624         Color fg = this.fg;
625         if ((e != null) && (e.getSource() == editor)) {
626             String JavaDoc s = e.getActionCommand();
627             try {
628             fg = Color.decode(s);
629             } catch (NumberFormatException JavaDoc nfe) {
630             }
631         }
632         if (fg != null) {
633             MutableAttributeSet JavaDoc attr = new SimpleAttributeSet JavaDoc();
634             StyleConstants.setForeground(attr, fg);
635             setCharacterAttributes(editor, attr, false);
636         } else {
637             UIManager.getLookAndFeel().provideErrorFeedback(editor);
638         }
639         }
640     }
641
642     private Color fg;
643     }
644
645     /**
646      * An action to set paragraph alignment. This sets the
647      * <code>StyleConstants.Alignment</code> attribute for the
648      * currently selected range of the target JEditorPane.
649      * This is done by calling
650      * <code>StyledDocument.setParagraphAttributes</code>
651      * on the styled document associated with the target
652      * JEditorPane.
653      * <p>
654      * If the target text component is specified as the
655      * source of the ActionEvent and there is a command string,
656      * the command string will be interpreted as an integer
657      * that should be one of the legal values for the
658      * <code>StyleConstants.Alignment</code> attribute.
659      * <p>
660      * <strong>Warning:</strong>
661      * Serialized objects of this class will not be compatible with
662      * future Swing releases. The current serialization support is
663      * appropriate for short term storage or RMI between applications running
664      * the same version of Swing. As of 1.4, support for long term storage
665      * of all JavaBeans<sup><font size="-2">TM</font></sup>
666      * has been added to the <code>java.beans</code> package.
667      * Please see {@link java.beans.XMLEncoder}.
668      */

669     public static class AlignmentAction extends StyledTextAction {
670
671         /**
672          * Creates a new AlignmentAction.
673          *
674          * @param nm the action name
675          * @param a the alignment >= 0
676          */

677     public AlignmentAction(String JavaDoc nm, int a) {
678         super(nm);
679         this.a = a;
680     }
681
682         /**
683          * Sets the alignment.
684          *
685          * @param e the action event
686          */

687         public void actionPerformed(ActionEvent JavaDoc e) {
688         JEditorPane JavaDoc editor = getEditor(e);
689         if (editor != null) {
690         int a = this.a;
691         if ((e != null) && (e.getSource() == editor)) {
692             String JavaDoc s = e.getActionCommand();
693             try {
694             a = Integer.parseInt(s, 10);
695             } catch (NumberFormatException JavaDoc nfe) {
696             }
697         }
698         MutableAttributeSet JavaDoc attr = new SimpleAttributeSet JavaDoc();
699         StyleConstants.setAlignment(attr, a);
700         setParagraphAttributes(editor, attr, false);
701         }
702     }
703
704     private int a;
705     }
706
707     /**
708      * An action to toggle the bold attribute.
709      * <p>
710      * <strong>Warning:</strong>
711      * Serialized objects of this class will not be compatible with
712      * future Swing releases. The current serialization support is
713      * appropriate for short term storage or RMI between applications running
714      * the same version of Swing. As of 1.4, support for long term storage
715      * of all JavaBeans<sup><font size="-2">TM</font></sup>
716      * has been added to the <code>java.beans</code> package.
717      * Please see {@link java.beans.XMLEncoder}.
718      */

719     public static class BoldAction extends StyledTextAction {
720
721         /**
722          * Constructs a new BoldAction.
723          */

724     public BoldAction() {
725         super("font-bold");
726     }
727
728         /**
729          * Toggles the bold attribute.
730          *
731          * @param e the action event
732          */

733         public void actionPerformed(ActionEvent JavaDoc e) {
734         JEditorPane JavaDoc editor = getEditor(e);
735         if (editor != null) {
736         StyledEditorKit JavaDoc kit = getStyledEditorKit(editor);
737         MutableAttributeSet JavaDoc attr = kit.getInputAttributes();
738         boolean bold = (StyleConstants.isBold(attr)) ? false : true;
739         SimpleAttributeSet JavaDoc sas = new SimpleAttributeSet JavaDoc();
740         StyleConstants.setBold(sas, bold);
741         setCharacterAttributes(editor, sas, false);
742         }
743     }
744     }
745
746     /**
747      * An action to toggle the italic attribute.
748      * <p>
749      * <strong>Warning:</strong>
750      * Serialized objects of this class will not be compatible with
751      * future Swing releases. The current serialization support is
752      * appropriate for short term storage or RMI between applications running
753      * the same version of Swing. As of 1.4, support for long term storage
754      * of all JavaBeans<sup><font size="-2">TM</font></sup>
755      * has been added to the <code>java.beans</code> package.
756      * Please see {@link java.beans.XMLEncoder}.
757      */

758     public static class ItalicAction extends StyledTextAction {
759
760         /**
761          * Constructs a new ItalicAction.
762          */

763     public ItalicAction() {
764         super("font-italic");
765     }
766
767         /**
768          * Toggles the italic attribute.
769          *
770          * @param e the action event
771          */

772         public void actionPerformed(ActionEvent JavaDoc e) {
773         JEditorPane JavaDoc editor = getEditor(e);
774         if (editor != null) {
775         StyledEditorKit JavaDoc kit = getStyledEditorKit(editor);
776         MutableAttributeSet JavaDoc attr = kit.getInputAttributes();
777         boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
778         SimpleAttributeSet JavaDoc sas = new SimpleAttributeSet JavaDoc();
779         StyleConstants.setItalic(sas, italic);
780         setCharacterAttributes(editor, sas, false);
781         }
782     }
783     }
784
785     /**
786      * An action to toggle the underline attribute.
787      * <p>
788      * <strong>Warning:</strong>
789      * Serialized objects of this class will not be compatible with
790      * future Swing releases. The current serialization support is
791      * appropriate for short term storage or RMI between applications running
792      * the same version of Swing. As of 1.4, support for long term storage
793      * of all JavaBeans<sup><font size="-2">TM</font></sup>
794      * has been added to the <code>java.beans</code> package.
795      * Please see {@link java.beans.XMLEncoder}.
796      */

797     public static class UnderlineAction extends StyledTextAction {
798
799         /**
800          * Constructs a new UnderlineAction.
801          */

802     public UnderlineAction() {
803         super("font-underline");
804     }
805
806         /**
807          * Toggles the Underline attribute.
808          *
809          * @param e the action event
810          */

811         public void actionPerformed(ActionEvent JavaDoc e) {
812         JEditorPane JavaDoc editor = getEditor(e);
813         if (editor != null) {
814         StyledEditorKit JavaDoc kit = getStyledEditorKit(editor);
815         MutableAttributeSet JavaDoc attr = kit.getInputAttributes();
816         boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
817         SimpleAttributeSet JavaDoc sas = new SimpleAttributeSet JavaDoc();
818         StyleConstants.setUnderline(sas, underline);
819         setCharacterAttributes(editor, sas, false);
820         }
821     }
822     }
823
824
825     /**
826      * StyledInsertBreakAction has similar behavior to that of
827      * <code>DefaultEditorKit.InsertBreakAction</code>. That is when
828      * its <code>actionPerformed</code> method is invoked, a newline
829      * is inserted. Beyond that, this will reset the input attributes to
830      * what they were before the newline was inserted.
831      */

832     static class StyledInsertBreakAction extends StyledTextAction {
833         private SimpleAttributeSet JavaDoc tempSet;
834
835         StyledInsertBreakAction() {
836             super(insertBreakAction);
837         }
838
839         public void actionPerformed(ActionEvent JavaDoc e) {
840             JEditorPane JavaDoc target = getEditor(e);
841
842             if (target != null) {
843         if ((!target.isEditable()) || (!target.isEnabled())) {
844             UIManager.getLookAndFeel().provideErrorFeedback(target);
845             return;
846         }
847                 StyledEditorKit JavaDoc sek = getStyledEditorKit(target);
848
849                 if (tempSet != null) {
850                     tempSet.removeAttributes(tempSet);
851                 }
852                 else {
853                     tempSet = new SimpleAttributeSet JavaDoc();
854                 }
855                 tempSet.addAttributes(sek.getInputAttributes());
856                 target.replaceSelection("\n");
857
858                 MutableAttributeSet JavaDoc ia = sek.getInputAttributes();
859
860                 ia.removeAttributes(ia);
861                 ia.addAttributes(tempSet);
862                 tempSet.removeAttributes(tempSet);
863             }
864             else {
865                 // See if we are in a JTextComponent.
866
JTextComponent JavaDoc text = getTextComponent(e);
867
868                 if (text != null) {
869                     if ((!text.isEditable()) || (!text.isEnabled())) {
870                 UIManager.getLookAndFeel().provideErrorFeedback(target);
871                         return;
872                     }
873                     text.replaceSelection("\n");
874                 }
875             }
876         }
877     }
878 }
879
Popular Tags