KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > TextEditor


1 /**
2  * Applet TextEditor
3  * <P>
4  * @authors: Stefanovic Nenad, Puskas Vladimir, Bojanic Sasa
5  * @Date: July-November 2001.
6  */

7
8 import java.lang.*;
9 import java.awt.*;
10 import java.awt.event.*;
11 import java.awt.datatransfer.*;
12 import java.util.*;
13 import java.beans.*;
14 import java.net.URL JavaDoc;
15 import javax.swing.*;
16 import javax.swing.event.*;
17 import javax.swing.text.*;
18 import javax.swing.text.html.*;
19
20
21 /** This applet class is used as a <b>text editor</b> that can return a
22  * <b>String</b> that represent a content of applet and is already formatted
23  * as a XSL:FO file. That String can be transformed into PDF file, which
24  * is achived by the use of FOP (FOP is Java application that reads a form
25  * of an XSL:FO and then turns it into a PDF document.).<p>
26  * Applet's text can be formatted in a different ways - every character can
27  * have their own font family and size and different style (bold, italic,
28  * underline), and every paragraph can have different alignment (left, center,
29  * right). Content of applet is transformed in a form of XSL:FO formatted string
30  * by calling applet's method FormatFO().<p>
31  * It is important to mention that applet's look and functionality is fully
32  * determined by the property files.
33 */

34  public class TextEditor extends JApplet{
35    int cnt=0;
36    /** String to use in methods accessing the properties file */
37    public static final String JavaDoc _fontfamily = "fontfamily";
38    /** String to use in methods accessing the properties file */
39    public static final String JavaDoc _fontsize = "fontsize";
40    /** String to use in methods accessing the properties file */
41    public static final String JavaDoc _family = "family";
42    /** String to use in methods accessing the properties file */
43    public static final String JavaDoc _size = "size";
44    /** String to use in methods accessing the properties file */
45    public static final String JavaDoc _label = "Label";
46    /** String to use in methods accessing the properties file */
47    public static final String JavaDoc _action = "Action";
48    /** String to use in methods accessing the properties file */
49    public static final String JavaDoc _tooltip = "Tooltip";
50    /** Limit on items in combobox */
51    public static final int _maxComboItems = 20;
52
53    /** Applet's toolbar */
54    private JToolBar toolbar;
55    /** Applet's menubar */
56    private JMenuBar MenuBar;
57    /** Font family combo box */
58    private JComboBox comboFontFamilies;
59    /** Font size combo box */
60    private JComboBox comboFontSizes;
61    /** Action Listener for combo boxes */
62    private ActionListener comboFontListener=new ActionListener() {
63       public void actionPerformed(ActionEvent e) {
64         comboFontActions(e);
65       }
66    };
67     /** Action Listener for toggle buttons */
68    private ActionListener toggleButtonListener=new ActionListener() {
69       public void actionPerformed(ActionEvent e) {
70         toggleButtonActions(e);
71       }
72    };
73    public static final String JavaDoc copyExtAction = "copyExt";
74    /** AttributeSet used to correct behaviour of new paragraph */
75    private SimpleAttributeSet currentAS;
76    /** boolean used to correct behaviour of new paragraph */
77    private boolean isEnterPressed=false;
78    /** boolean used to correct behaviour of new paragraph */
79    private boolean isBSValid=false;
80    /** An instance of text editor */
81    private MyTextPane editor;
82    /** Contains possible editor actions */
83    private Hashtable commands;
84   /** Declaration of "main" resource file */
85    private static ResourceBundle resources;
86    /** Texts for "language" default resource bundle **/
87    private static ResourceBundle resdef;
88    /** Texts for resource bundle **/
89    private static ResourceBundle resText;
90    /** Name of resource(property) file */
91    String JavaDoc res;
92    /** String for identifing using language **/
93    String JavaDoc resLan;
94    /** Editor's document root elements (section and paragraphs) */
95    private Element[] rootElements;
96     /** Popup menu for TextEditor**/
97    private JPopupMenu PopUp;
98    /** Toolbar's toggle button for getting bold character style */
99    private JToggleButton boldButton;
100    /** Toolbar's toggle button for getting italic character style */
101    private JToggleButton italicButton;
102    /** Toolbar's toggle button for getting underline character style */
103    private JToggleButton underButton;
104    /** Toolbar's toggle button for getting left paragraph alignment */
105    private JToggleButton leftButton;
106    /** Toolbar's toggle button for getting center paragraph alignment */
107    private JToggleButton centerButton;
108    /** Toolbar's toggle button for getting right paragraph alignment */
109    private JToggleButton rightButton;
110    /** Group for togglebuttons left,cenetr,right */
111    private ButtonGroup group=new ButtonGroup();
112    /**
113     * Predefined default line-height value used when formating applet context
114     * into a form of XSL:FO format. If there is no such value in property file
115     * this one will be used
116     */

117    private String JavaDoc defLineHeight="18";
118    /**
119     * Predefined default language specification value for hyphenation. If there is no
120     * such value in property file, this one will be used
121     */

122    private String JavaDoc defHyph="en";
123    // There are some predefined default font values if no one exist in property file.
124
/**
125     * Predefined default font family value. Possible values for fontfamily are:
126     * 'SansSerif'(Helvetica), 'Serif'(TimesRoman) and 'Monospaced'(Courier).
127     */

128    private String JavaDoc defFontFamily="Serif";
129    /** Predefined default font size value. Possible values for font size are:
130    * 8, 10, 12, 14, 16, 18, 24, 36 and 48.
131    */

132    private String JavaDoc defFontSize="16";
133    /** Predefined default bold font style value. Possible values are true and false */
134    private boolean defbold=false;
135    /** Predefined default italic font style value. Possible values are true and false */
136    private boolean defitalic=false;
137    /** Predefined default underline font style value. Possible values are true and false */
138    private boolean defunder=false;
139    /**
140     * Returns the value of parameter <b>key</b> in the HTML tag, or
141     * default value <b>def</b> if doesn't find it. For example, if
142     * HTML document referencing this applet contains line:<BR>
143     * <CENTER>&ltPARAM NAME="Resource" VALUE="TextEditor"&gt</CENTER>
144     * then a call to getParameter("Resource","TEX") returns the value
145     * "TextEditor". If this line doesn't exist in HTML document,
146     * the same call to this method will return the value "TEX".
147     * @param key a parameter name
148     * @param def default value for the parameter
149     * @return the value of parameter, or default value if not set
150     */

151    public String JavaDoc getParameter(String JavaDoc key, String JavaDoc def) {
152       if (getParameter(key) != null) {
153          return getParameter(key);
154       }
155       return def;
156    }
157
158    /** There's nothing to do within the constructor */
159    public TextEditor() {
160    }
161    /**
162     * Initializes the state of this instance. Gets the name of the "main" property file
163     * to use and language to use from HTML tag, sets the 'look and feel' of applet
164     * to the system one, gets the "main" and "language" property files declaration,
165     * and calls the function jbInit for further creation and initialization of the applet.
166     */

167    public void init() {
168       // taking parametars from HTML document
169
res = getParameter("Resource", "TextEditor");
170       resLan=getParameter("Language","");
171       // setting 'look and feel'
172
try {
173          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
174       }
175       catch(Exception JavaDoc e) {
176          e.printStackTrace();
177       }
178       // reading property files
179
try {
180          resources = ResourceBundle.getBundle(res);
181       }
182       catch (MissingResourceException MRe) {
183          System.err.println(res+".properties not found");
184          System.exit(0);
185       }
186         try {
187          resdef=ResourceBundle.getBundle("Text");
188       }
189       catch (MissingResourceException MRe) {
190          System.err.println("Text.properties not found");
191          System.exit(0);
192       }
193       try {
194         resText=ResourceBundle.getBundle("Text_"+resLan);
195       }
196       catch (MissingResourceException MRe) {
197          resText=ResourceBundle.getBundle("Text");
198          System.err.println("Text_"+resLan+".properties not found, using default Text.properties !!!");
199       }
200       super.init();
201       try {
202          jbInit();
203       }
204       catch (Exception JavaDoc e) {
205          e.printStackTrace();
206       }
207
208    }
209    /** Main method for creating and initializing applet. Creates the
210     * Editor, adds him a Mouse, Caret and Key listener. Sets Editor's
211     * look and menubar and toolbar
212    */

213    protected void jbInit() throws Exception JavaDoc {
214       // Dimensions of applet
215
setSize(new Dimension(600, 400));
216       // Seting up for main jPanel
217
JPanel Glavni = new JPanel();
218       Glavni.setBorder(BorderFactory.createEtchedBorder());
219       Glavni.setLayout(new BorderLayout());
220       //Creating a editor for TextEditor
221
editor=createEditor();
222       editor.addMouseListener(new PopMouseListener());
223       editor.addCaretListener(new CaretListener(){
224          public void caretUpdate(CaretEvent e) {
225             caretChange(e);
226          }
227       });
228       editor.addKeyListener(new KeyAdapter(){
229          public void keyPressed(KeyEvent e){
230             int keyCode=e.getKeyCode();
231             if ((keyCode==KeyEvent.VK_ENTER) || (keyCode==KeyEvent.VK_BACK_SPACE)) {
232                StyledDocument theDocument = getEditor().getStyledDocument();
233                int dot = getEditor().getCaret().getDot();
234                //current paragraph
235
Element prgel=theDocument.getParagraphElement(dot);
236                // start and end of current paragraph
237
int stof=prgel.getStartOffset();
238                int enof=prgel.getEndOffset();
239
240                // if back space is pressed at the place that will not empty the
241
// paragraph, return
242
if (keyCode==KeyEvent.VK_BACK_SPACE && !(dot==stof+1 && enof==stof+2)) {
243                   return;
244                }
245
246                // current paragraph and character attributes
247
AttributeSet cpas=getEditor().getParagraphAttributes();
248                AttributeSet ccas=editor.getInputAttributes();
249
250                currentAS=new SimpleAttributeSet(cpas);
251
252                StyleConstants.setFontFamily(currentAS,StyleConstants.getFontFamily(ccas));
253                StyleConstants.setFontSize(currentAS,StyleConstants.getFontSize(ccas));
254                StyleConstants.setBold(currentAS,StyleConstants.isBold(ccas));
255                StyleConstants.setItalic(currentAS,StyleConstants.isItalic(ccas));
256                StyleConstants.setUnderline(currentAS,StyleConstants.isUnderline(ccas));
257
258                if (keyCode==KeyEvent.VK_ENTER) {
259                   isEnterPressed=true;
260                }
261                if (keyCode==KeyEvent.VK_BACK_SPACE) {
262                   isBSValid=true;
263                }
264
265                // if Enter is pressed at an empty paragraph, change it's setting
266
if ((dot==stof) && (enof-stof==1) && (keyCode==KeyEvent.VK_ENTER)) {
267                   editor.setParagraphAttributes(currentAS,true);
268                }
269             }
270          }
271
272          public void keyTyped(KeyEvent e){
273             int keyCode=e.getKeyChar();
274             // in the case of 'backspacing' to the begining, attribute
275
// setup mustn't change to something different
276
if (keyCode==KeyEvent.VK_BACK_SPACE) {
277                if (isBSValid) {
278                   int dot = getEditor().getCaret().getDot();
279                   StyledDocument theDocument = getEditor().getStyledDocument();
280                   //current paragraph
281
Element prgel=theDocument.getParagraphElement(dot);
282                   // start and end of current paragraph
283
int stof=prgel.getStartOffset();
284                   int enof=prgel.getEndOffset();
285                   if (enof > theDocument.getLength()) {
286                     enof=theDocument.getLength();
287                   }
288                   editor.moveCaretPosition(enof);
289                   editor.setParagraphAttributes(currentAS,true);
290                   editor.setCharacterAttributes(currentAS,true);
291                   editor.moveCaretPosition(dot);
292                   isBSValid=false;
293                }
294             }
295
296             if (keyCode==KeyEvent.VK_ENTER && isEnterPressed==true) {
297                editor.setParagraphAttributes(currentAS,true);
298                editor.setCharacterAttributes(currentAS,true);
299                isEnterPressed=false;
300             }
301          }
302
303       });
304       // Install the command table in Hashtable
305
commands = new Hashtable();
306       Action[] actions = getActions();
307       for (int i = 0; i < actions.length; i++) {
308          Action a = actions[i];
309          commands.put(a.getValue(Action.NAME), a);
310       }
311       JScrollPane scroll = new JScrollPane();
312       JViewport port = scroll.getViewport();
313       port.add(editor);
314       if (getResourceString("menubar")!=null)
315          MenuBar=createMenuBar();
316       JPanel panel=new JPanel();
317       Glavni.add(scroll,BorderLayout.CENTER);
318       if (getResourceString("toolbar")!=null)
319          Glavni.add(createToolbar(),BorderLayout.NORTH);
320       //Adding a JMenuBar to the applet
321
this.setJMenuBar(MenuBar);
322       this.getContentPane().add(Glavni);
323       setContentPane(Glavni);
324       editor.requestFocus();
325    }
326    /**
327     * Creates an editor for TextEditor applet. Sets the default values of fonts
328     * and colors for editor.
329     * @return created editor (instance of class MyTextPane).
330     */

331    protected MyTextPane createEditor(){
332       editor=new MyTextPane();
333       // Setting a default values for document
334
StyleContext sc = new StyleContext();
335       DefaultStyledDocument doc = new DefaultStyledDocument(sc);
336       editor.setStyledDocument(doc);
337
338       // Setting a default values for editor
339
setDefaultFonts();
340       setDefaultColors();
341
342       // Setting default style to match default values
343
Style def = sc.getStyle(StyleContext.DEFAULT_STYLE);
344       StyleConstants.setFontFamily(def,defFontFamily);
345       StyleConstants.setFontSize(def,Integer.parseInt(defFontSize));
346       StyleConstants.setBold(def,defbold);
347       StyleConstants.setItalic(def,defitalic);
348       StyleConstants.setUnderline(def,defunder);
349
350       return editor;
351    }
352    /**
353     * Setting up a default font values for editor. The default values are
354     * read from "main" property file. If no default values is defined in
355     * the resource file, there are some predefined values.
356     */

357    protected void setDefaultFonts(){
358       MutableAttributeSet defAtt=editor.getInputAttributes();
359       try{
360          String JavaDoc[] defKeys = tokenize(getResourceString("defvalues"));
361          String JavaDoc[] keyval=new String JavaDoc[defKeys.length];
362          for (int i = 0; i < defKeys.length; i++) {
363             keyval[i]=getResourceString(defKeys[i]);
364             if (defKeys[i].equals("defFontFamily")){
365                String JavaDoc ff=keyval[i].toString();
366                if (validateDefaults(_family,ff))
367                   defFontFamily=ff;
368             }
369             else if (defKeys[i].equals("defFontSize")){
370                String JavaDoc fs=keyval[i].toString();
371                if (validateDefaults(_size,fs))
372                   defFontSize=fs;
373             }
374             else if (defKeys[i].equals("defbold")){
375                String JavaDoc bld=keyval[i].toString();
376                if (bld.equals("true"))
377                   defbold=true;
378             }
379             else if (defKeys[i].equals("defitalic")){
380                String JavaDoc itl=keyval[i].toString();
381                if (itl.equals("true"))
382                   defitalic=true;
383             }
384             else if (defKeys[i].equals("defunder")){
385                String JavaDoc und=keyval[i].toString();
386                if (und.equals("true"))
387                   defunder=true;
388             }
389          }
390       }
391       catch(Exception JavaDoc e){
392          System.err.println("There is no default values for editor in property file");
393       }
394       int defFSi=Integer.parseInt(defFontSize);
395       // Defining fontfamily
396
StyleConstants.setFontFamily(defAtt,defFontFamily);
397       // Defining fontsize
398
StyleConstants.setFontSize(defAtt, defFSi);
399       // Defining fontstyle
400
StyleConstants.setBold(defAtt,defbold);
401       StyleConstants.setItalic(defAtt,defitalic);
402       StyleConstants.setUnderline(defAtt,defunder);
403     // reading value for line-height
404
String JavaDoc strLH=getResourceString("lineHeight");
405     int intLH;
406     // some checking
407
try {
408         intLH=Integer.parseInt(strLH);
409         if (intLH>=8 && intLH<=96) {
410             defLineHeight=strLH;
411         }
412         else {
413             if (intLH<8) defLineHeight="8";
414             else defLineHeight="96";
415             System.err.println("Warning, line height value should be beetwen 8 and 96, using value of "+defLineHeight);
416         }
417     }
418     catch (Exception JavaDoc e) {
419         System.err.println("Error reading lineHeight parameter, using predefined value of "+defLineHeight);
420     }
421       //reading lanuage specification value for hyphenation
422
String JavaDoc strHyph=getResourceString("defHyphen");
423       if (strHyph==null)
424          System.out.println("Error while reading defHyphen parameter, using predefined value: "+defHyph);
425       else
426          defHyph=strHyph;
427    }
428    /** Method for validating default values of font family and font size
429     * from "main" property file (and programs default values). This method is
430     * caled from method setDefaultFonts().<BR>
431     * Default value specified in the property file must be one of possible
432     * values, also specified in property file. If this value matches the one of
433     * possible values, method returns <b>true</b>, otherwise, if default value
434     * isn't specified correctly or isn't specified at all, this method returns
435     * <b>false</b>, which tells program to use the default value specified by
436     * the program itself. In that case this method, before returning <b>false</b>,
437     * also verifies the program default value, and if such doesn't exist in the
438     * property file, the program default value becomes the first of possible values
439     * specified in property file.
440     * @param key name of default value to validate ("family" or "size")
441     * @param value default value attained from property file
442     * @return wether property file default value is OK (<b>true</b>) or not (<b>false</b>
443     */

444    private boolean validateDefaults (String JavaDoc key,String JavaDoc value) {
445 // reading possible values of font-size or font-family from
446
// property file and putting it into vector
447
int i = 1;
448       Vector vecSizesOrFamilies=new Vector();
449       int substrstart;
450       if (key.equals(_size)) substrstart=10;
451       else substrstart=12;
452         for( String JavaDoc action; null !=( action = getResourceString( key + i + _action )); ++i ) {
453 // must remove 'font-size-' or 'font-family-' from action string
454
// to get the size or family of the font
455
action=action.substring(substrstart);
456             vecSizesOrFamilies.addElement(action);
457       }
458 // validating value
459
if (vecSizesOrFamilies.contains(value)) {
460          return true;
461       }
462       else {
463 // validating if default program values are corresponding to
464
// those possibile in property file, if not, changing them
465
if (key.equals(_size)) {
466             if(!(vecSizesOrFamilies.contains(defFontSize)) &&
467                !(vecSizesOrFamilies.isEmpty()))
468                defFontSize=(String JavaDoc)vecSizesOrFamilies.firstElement();
469          }
470          else {
471             if(!(vecSizesOrFamilies.contains(defFontFamily)) &&
472                !(vecSizesOrFamilies.isEmpty()))
473                defFontFamily=(String JavaDoc)vecSizesOrFamilies.firstElement();
474          }
475          return false;
476       }
477    }
478    /**
479     * Setting up a default color values for editor. These values are read
480     * from "main" property file. If no default values is defined in property
481     * file, there are some predefined values.
482     */

483    protected void setDefaultColors(){
484       /** Predefined default color values **/
485       Color foreground=Color.green;
486       Color background=Color.black;
487       Color caretColor=Color.yellow;
488       Color selectedTextColor=Color.yellow;
489       Color selectionColor=Color.lightGray;
490       Color border=SystemColor.info;
491       /**
492        * Standard colors are:
493          * black,blue,cyan,darkGray,gray,green,lightGray,magenta,orange,pink,red,white,yellow
494        * Also, there are many system colors like:
495        * activeCaption,control,controlShadow,controlText,desktop,inactiveCaptionText,info,
496        * infoText,menu,menuText,scrollbar,text,window,windowBorder,windowText etc...
497        */

498       /** string array containing names of possible colors to set **/
499       String JavaDoc strCol[]={"Color.black","Color.blue","Color.cyan","Color.darkGray","Color.gray",
500                         "Color.green","Color.lightGray","Color.magenta","Color.orange",
501                         "Color.pink","Color.red","Color.white","Color.yellow",
502                         "SystemColor.desktop","SystemColor.activeCaption",
503                         "SystemColor.activeCaptionText","SystemColor.activeCaptionBorder",
504                         "SystemColor.inactiveCaption","SystemColor.inactiveCaptionText",
505                         "SystemColor.inactiveCaptionBorder","SystemColor.window",
506                         "SystemColor.windowBorder","SystemColor.windowText",
507                         "SystemColor.menu","SystemColor.menuText","SystemColor.text",
508                         "SystemColor.textText","SystemColor.textHighlight",
509                         "SystemColor.textHighlightText","SystemColor.textInactiveText",
510                         "SystemColor.control","SystemColor.controlText",
511                         "SystemColor.controlHighlight","SystemColor.controlLtHighlight",
512                         "SystemColor.controlShadow","SystemColor.controlDkShadow",
513                         "SystemColor.scrollbar","SystemColor.info","SystemColor.infoText"};
514       /** Color array containing possible colors to set **/
515       Color colCol[]={Color.black,Color.blue,Color.cyan,Color.darkGray,Color.gray,
516                         Color.green,Color.lightGray,Color.magenta,Color.orange,
517                         Color.pink,Color.red,Color.white,Color.yellow,
518                         SystemColor.desktop,SystemColor.activeCaption,
519                         SystemColor.activeCaptionText,SystemColor.activeCaptionBorder,
520                         SystemColor.inactiveCaption,SystemColor.inactiveCaptionText,
521                         SystemColor.inactiveCaptionBorder,SystemColor.window,
522                         SystemColor.windowBorder,SystemColor.windowText,
523                         SystemColor.menu,SystemColor.menuText,SystemColor.text,
524                         SystemColor.textText,SystemColor.textHighlight,
525                         SystemColor.textHighlightText,SystemColor.textInactiveText,
526                         SystemColor.control,SystemColor.controlText,
527                         SystemColor.controlHighlight,SystemColor.controlLtHighlight,
528                         SystemColor.controlShadow,SystemColor.controlDkShadow,
529                         SystemColor.scrollbar,SystemColor.info,SystemColor.infoText};
530       // Vectors for manipulating previous arrays
531
Vector vStrCol=new Vector();
532       Vector vColCol=new Vector();
533       for (int i=0; i<strCol.length;i++) {
534          vStrCol.addElement(strCol[i]);
535          vColCol.addElement(colCol[i]);
536       }
537       // Reading the default values from resource file
538
try{
539          String JavaDoc[] defKeys = tokenize(getResourceString("defvalues"));
540          String JavaDoc[] keyval=new String JavaDoc[defKeys.length];
541          for (int i = 0; i < defKeys.length; i++) {
542             keyval[i]=getResourceString(defKeys[i]);
543             if (defKeys[i].equals("foreground")){
544                foreground=getColor(keyval[i],foreground,vStrCol,vColCol);
545             }
546             else if (defKeys[i].equals("background")){
547                background=getColor(keyval[i],background,vStrCol,vColCol);
548             }
549             else if (defKeys[i].equals("caretColor")){
550                caretColor=getColor(keyval[i],caretColor,vStrCol,vColCol);
551             }
552             else if (defKeys[i].equals("selectedTextColor")){
553                selectedTextColor=getColor(keyval[i],selectedTextColor,vStrCol,vColCol);
554             }
555             else if (defKeys[i].equals("selectionColor")){
556                selectionColor=getColor(keyval[i],selectionColor,vStrCol,vColCol);
557             }
558             else if (defKeys[i].equals("border")){
559                border=getColor(keyval[i],border,vStrCol,vColCol);
560             }
561          }
562       }
563       catch(Exception JavaDoc e){
564          System.err.println("There is no default values for editor in property file");
565       }
566       // Defining foreground color
567
editor.setForeground(foreground);
568       // Defining background color
569
editor.setBackground(background);
570       // Defining caret color
571
editor.setCaretColor(caretColor);
572       // Defining color of selected text
573
editor.setSelectedTextColor(selectedTextColor);
574       // Defining color of selection
575
editor.setSelectionColor(selectionColor);
576       // Defining border color
577
editor.setBorder(BorderFactory.createLineBorder(border,1));
578    }
579    /**
580     * Method for determining default color values from property file.
581     * Method returns default color value specified in the property file
582     * if that value is one of possibile values (Color.black, Color.blue, ...),
583     * or program predefined value otherwise.
584     * @param strColor default color from property file to check
585     * @param defColor predefined color to set if <b>strColor</b> doesn't pass the test
586     * @param vStrColor vector of possible color names
587     * @param vColColor vector of possible colors (corresponds to the vector vStrCol)
588     * @return <b>Color</b> to be set (either one from property file, either predefined one)
589     */

590    private Color getColor(String JavaDoc strColor,Color defColor,Vector vStrCol,Vector vColCol) {
591       Color colorVal=defColor;
592       if (vStrCol.contains(strColor)) {
593          int ind=vStrCol.indexOf(strColor);
594          colorVal=(Color)vColCol.elementAt(ind);
595       }
596       return colorVal;
597    }
598    /**
599     * Creates the menubar for the applet. Reads the property file to
600     * determine which menus to create, then creates and puts
601     * them on menubar.
602     * @return created menubar.
603     */

604    protected JMenuBar createMenuBar(){
605       JMenuItem mi;
606       JMenuBar mb = new JMenuBar();
607       String JavaDoc[] menuKeys = tokenize(getResourceString("menubar"));
608       for (int i = 0; i < menuKeys.length; i++) {
609          JMenu m = createMenu(menuKeys[i]);
610          if (m != null)
611             mb.add(m);
612       }
613       return mb;
614    }
615    /**
616     * Creates a menu for the menubar of the applet. Reads the property file to
617     * set the menu name, to determine which menu items to create, then
618     * creates and puts them in the menu.
619     * @param key name of menu to search for in property file and create.
620     * @return created menu.
621     */

622    protected JMenu createMenu(String JavaDoc key) {
623       String JavaDoc[] itemKeys = tokenize(getResourceString(key));
624       JMenu menu = new JMenu(getResourceString(key + "Label"));
625       menu.setMnemonic(menu.getText().charAt(0));
626       for (int i = 0; i < itemKeys.length; i++) {
627          if (itemKeys[i].equals("-")) {
628             menu.addSeparator();
629          }
630          else {
631             JMenuItem mi = createMenuItem(itemKeys[i]);
632             menu.add(mi);
633          }
634       }
635       return menu;
636    }
637    /**
638     * Creates a menuitems for the menu. Reads the property file to set
639     * the menu item name, icon and action. For info menu items, defines
640     * the action listener.
641     * @param cmd the name of menu item.
642     * @return created menu item.
643     */

644    protected JMenuItem createMenuItem(String JavaDoc cmd) {
645       JMenuItem mi = new JMenuItem(getResourceString(cmd + "Label"));
646       if (cmd.equals("about")){
647          // Action listener for About window
648
mi.addActionListener(new ActionListener(){
649             public void actionPerformed(ActionEvent e){
650                helpAbout(e);
651             }
652          });
653       }
654       else if (cmd.equals("parametar")){
655          // Action listener for ParametarInfo window
656
mi.addActionListener(new ActionListener(){
657             public void actionPerformed(ActionEvent e){
658                helpParam(e);
659             }
660          });
661       }
662       else{
663          URL JavaDoc url = getResource(cmd + "ImageMenu");
664          if (url != null) {
665             mi.setHorizontalTextPosition(JButton.RIGHT);
666             mi.setIcon(new ImageIcon(url));
667          }
668          String JavaDoc astr = getResourceString(cmd + "Action");
669          if (astr == null) astr = cmd;
670          final String JavaDoc astrf=astr;
671          final String JavaDoc cmdf=cmd;
672          mi.setActionCommand(astrf);
673          final Action a = getAction(astrf);
674          if (a != null) {
675 // linking format menu items with toolbar buttons and combos - must define Action Listener
676
if (astrf.substring(0,4).equals("font")) {
677                if (cmdf.equals("bold")) {
678                   mi.addActionListener(new ActionListener() {
679                      public void actionPerformed(ActionEvent ae) {
680                         a.actionPerformed(ae);
681                         if (boldButton!=null) {
682                            boldButton.setSelected(!boldButton.isSelected());
683                         }
684                      }
685                   });
686                }
687                else if (cmdf.equals("italic")) {
688                   mi.addActionListener(new ActionListener() {
689                      public void actionPerformed(ActionEvent ae) {
690                         a.actionPerformed(ae);
691                         if (italicButton!=null) {
692                            italicButton.setSelected(!italicButton.isSelected());
693                         }
694                      }
695                   });
696                }
697                else if (cmdf.equals("underline")) {
698                   mi.addActionListener(new ActionListener() {
699                      public void actionPerformed(ActionEvent ae) {
700                         a.actionPerformed(ae);
701                         if (underButton!=null) {
702                            underButton.setSelected(!underButton.isSelected());
703                         }
704                      }
705                   });
706                }
707                else if (astrf.substring(5,9).equals(_size)) {
708                   mi.addActionListener(new ActionListener() {
709                      public void actionPerformed(ActionEvent ae) {
710                         a.actionPerformed(ae);
711                         if (comboFontSizes!=null) {
712                            comboFontSizes.removeActionListener(comboFontListener);
713                            comboFontSizes.setSelectedItem(getResourceString(cmdf + _label));
714                            comboFontSizes.addActionListener(comboFontListener);
715                         }
716                      }
717                   });
718                }
719                else if (astrf.substring(5,11).equals(_family)) {
720                   mi.addActionListener(new ActionListener() {
721                      public void actionPerformed(ActionEvent ae) {
722                         a.actionPerformed(ae);
723                         if (comboFontFamilies!=null) {
724                            comboFontFamilies.removeActionListener(comboFontListener);
725                            comboFontFamilies.setSelectedItem(getResourceString(cmdf + _label));
726                            comboFontFamilies.addActionListener(comboFontListener);
727                         }
728                      }
729                   });
730                }
731             }
732             else {
733                mi.addActionListener(a);
734             }
735             mi.setEnabled(a.isEnabled());
736          }
737          else mi.setEnabled(false);
738       }
739       return mi;
740    }
741   /**
742      * Gets a resource string from the resource bundle.<p> Resource bundle
743      * represents the <i>property file</i>. For example, if property file
744      * contains something like this:<BR><CENTER>menubar=edit format info</CENTER>
745     * method call getResourceString("menubar") will give the string
746     * <i>edit format info</i> as a result. <BR> This method reads information
747     * from "main" property file, if can't find desired resource, searchs the "language"
748     * property file, and if still can't find it searchs the default "language" property file.
749     * If can't find desired resource in either of these files, returns <b>null</b>.
750      * @param nm name of the resource to fetch.
751     * @return String value of named resource.
752      */

753    protected String JavaDoc getResourceString(String JavaDoc nm) {
754       String JavaDoc str;
755       try {
756          str = this.resources.getString(nm);
757       }
758       catch (MissingResourceException mre) {
759          try {
760             str = this.resText.getString(nm);
761          }
762          catch (MissingResourceException mree) {
763             try {
764                str = this.resdef.getString(nm);
765             }
766             catch (MissingResourceException mreee) {
767                str = null;
768             }
769          }
770       }
771       if (str != null) str=str.trim();
772       return str;
773    }
774    /**
775     * Gets a url from a resource string.
776     * @param key the string key to the url in the resource bundle.
777     * @return the resource location.
778     * @see java.lang.Class#getResource
779     */

780    protected URL JavaDoc getResource(String JavaDoc key) {
781     String JavaDoc name = getResourceString(key);
782        if (name != null) {
783           URL JavaDoc url = this.getClass().getResource(name);
784           return url;
785        }
786        return null;
787    }
788    /**
789     * Take the given string and chop it up into a series
790     * of strings on whitespace boundaries.
791     * @param input string to 'tokenize'
792     * @return 'tokenized' string array
793     */

794    public static String JavaDoc[] tokenize(String JavaDoc input) {
795       Vector v = new Vector();
796       StringTokenizer t = new StringTokenizer(input);
797       String JavaDoc cmd[];
798       while (t.hasMoreTokens())
799          v.addElement(t.nextToken());
800       cmd = new String JavaDoc[v.size()];
801       for (int i = 0; i < cmd.length; i++)
802          cmd[i] = (String JavaDoc) v.elementAt(i);
803       return cmd;
804    }
805    /**
806     * Method to get all actions suported by the class JTextPane.
807     * @return Returns all supported editor's actions.
808     **/

809    public Action[] getActions() {
810       Action[] defaultActions = {
811          new CopyExtAction()};
812       Action[] a = TextAction.augmentList(editor.getActions(), defaultActions);
813 /*
814         Action[] defaultActions = {
815             new NewAction(),
816             new OpenAction(),
817             new SaveAction(),
818             new StyledEditorKit.FontFamilyAction("font-family-LucidaSans",
819                                                  "Lucida Sans"),
820         };
821         Action[] a = TextAction.augmentList(super.getActions(), defaultActions);
822
823  */

824     // return editor.getActions();
825
return a;
826    }
827    /**
828     * Method to get editor's action corresponding to the given string.
829     * @param cmd String representation of editor's action.
830     * @return action specified by the string cmd.
831     **/

832    protected Action getAction(String JavaDoc cmd) {
833       return (Action) commands.get(cmd);
834    }
835    /**
836     * Public method for accessing private class member editor
837     * @return an editor (instance of class MyTextPane).
838     **/

839    public JTextPane getEditor() {
840       return editor;
841    }
842    /**
843     * Creates the toolbar for editor. Reads the property file to
844     * determine which tool buttons to create, then creates and puts
845     * them on toolbar.
846     * @return created toolbar.
847     */

848    protected Component createToolbar() {
849       toolbar = new JToolBar();
850       String JavaDoc[] toolKeys = tokenize(getResourceString("toolbar"));
851       for (int i = 0; i < toolKeys.length; i++) {
852          if (toolKeys[i].equals("-")) {
853             toolbar.add(Box.createHorizontalStrut(10));
854          }
855          else {
856             toolbar.add(createTool(toolKeys[i]));
857          }
858       }
859       toolbar.add(Box.createHorizontalGlue());
860       JButton but=new JButton("Dump");
861       but.addActionListener(new ActionListener() {
862          public void actionPerformed(ActionEvent e) {
863             testing(e);
864          }
865       });
866       /** For testing purposes only **/
867       //toolbar.add(but);
868
/** By default, alignment is left**/
869       leftButton.setSelected(true);
870       return toolbar;
871    }
872    /**
873     * Hook through which every toolbar item is created. This method calls
874     * other methods for creating toolbar items, depending of what item is
875     * to be created.
876     * @param key name of item to be created.
877     * @return created component (JComboBox, JToggleButton, JToggleGroup or JButton).
878     */

879    protected Component createTool(String JavaDoc key) {
880       if (key.equals("fontfamily") || key.equals("fontsize"))
881          return createComboBoxes(key);
882       else if(key.equals("bold") || key.equals("italic") || key.equals("underline")){
883          return createToggleButton(key);
884       }
885       else if(key.equals("left") || key.equals("center") || key.equals("right")){
886          return createToggleGroup(key);
887       }
888       else
889         return createToolbarButton(key);
890    }
891    /** Creates the toggle button's group. Within this group,
892     * only one button at a time is active. This method creates toggle button
893     * by the call to the method everyToggle(), and then sets the button's
894     * action and tooltip text.
895     * @param key name of the toggle button that belongs to the toggle group and
896     * is to be created.
897     * @return created toggle button.
898     */

899    protected JToggleButton createToggleGroup(String JavaDoc key){
900       JToggleButton Tb = everyToggle(key);
901       Tb.setRequestFocusEnabled(false);
902       Tb.setMargin(new Insets(1,1,1,1));
903       String JavaDoc astr = getResourceString(key + "Action");
904       if (astr == null) {
905          astr = key;
906       }
907       Action a = getAction(astr);
908       if (a != null) {
909          Tb.setActionCommand(astr);
910          Tb.addActionListener(a);
911       }
912       else {
913          Tb.setEnabled(false);
914       }
915       String JavaDoc tip = getResourceString(key + "Tooltip");
916       if (tip != null) {
917          Tb.setToolTipText(tip);
918       }
919       group.add(Tb);
920       return Tb;
921    }
922    /**
923     * This method is called as a result of selecting menu item <i>About</i> from
924     * <i>Info</i> menu. Shows message dialog filled with 'about' data.
925     * @param e ActionEvent to react upon
926     */

927    private void helpAbout(ActionEvent e){
928       JOptionPane.showMessageDialog(this, new InfoPanel(), getResourceString("aboutLabel"), JOptionPane.INFORMATION_MESSAGE);
929    }
930    /**
931     * This method is called as a result of selecting menu item <i>Parameter info</i> from
932     * <i>Info</i> menu. Shows message dialog filled with 'parameter info' data.
933     * @param e ActionEvent to react upon
934     */

935    private void helpParam(ActionEvent e){
936       JOptionPane.showMessageDialog(this, new InfoPanel(resources,resLan,res,defHyph), getResourceString("parametarLabel"), JOptionPane.INFORMATION_MESSAGE);
937    }
938    /**
939     * Creates instances of ToggleButtons. For each button sets the icon and
940     * default state determined by property file or predefined.
941     * @param name name of toggle buton to be created.
942     * @return created toggle button.
943     */

944     protected JToggleButton everyToggle(String JavaDoc name){
945     URL JavaDoc url = getResource(name + "ImageTool");
946       if (name.equals("bold")){
947         try {
948             boldButton=new JToggleButton(new ImageIcon(url),defbold){
949                 public float getAlignmentY() { return 0.5f; }
950             };
951         }
952         catch (Exception JavaDoc e) {
953             boldButton=new JToggleButton(name,defbold){
954                 public float getAlignmentY() { return 0.5f; }
955             };
956         }
957         return boldButton;
958       }
959       else if (name.equals("italic")){
960         try {
961             italicButton=new JToggleButton(new ImageIcon(url),defitalic){
962                 public float getAlignmentY() { return 0.5f; }
963             };
964         }
965         catch (Exception JavaDoc e) {
966             italicButton=new JToggleButton(name,defitalic){
967                 public float getAlignmentY() { return 0.5f; }
968             };
969         }
970         return italicButton;
971       }
972       else if(name.equals("underline")){
973         try {
974             underButton=new JToggleButton(new ImageIcon(url),defunder){
975                 public float getAlignmentY() { return 0.5f; }
976             };
977         }
978         catch (Exception JavaDoc e) {
979             underButton=new JToggleButton(name,defunder){
980                 public float getAlignmentY() { return 0.5f; }
981             };
982         }
983         return underButton;
984       }
985       else if(name.equals("left")){
986         try {
987             leftButton=new JToggleButton(new ImageIcon(url),false){
988                 public float getAlignmentY() { return 0.5f; }
989             };
990         }
991         catch (Exception JavaDoc e) {
992             leftButton=new JToggleButton(name,false){
993                 public float getAlignmentY() { return 0.5f; }
994             };
995         }
996         return leftButton;
997       }
998       else if(name.equals("center")){
999         try {
1000            centerButton=new JToggleButton(new ImageIcon(url),false){
1001                public float getAlignmentY() { return 0.5f; }
1002            };
1003        }
1004        catch (Exception JavaDoc e) {
1005            centerButton=new JToggleButton(name,false){
1006                public float getAlignmentY() { return 0.5f; }
1007            };
1008        }
1009        return centerButton;
1010      }
1011      else {
1012        try {
1013            rightButton=new JToggleButton(new ImageIcon(url),false){
1014                public float getAlignmentY() { return 0.5f; }
1015            };
1016        }
1017        catch (Exception JavaDoc e) {
1018            rightButton=new JToggleButton(name,false){
1019                public float getAlignmentY() { return 0.5f; }
1020            };
1021        }
1022        return rightButton;
1023      }
1024   }
1025   /**
1026    * Creating a ToggleButtons for actions: Bold, Italic, Underline.
1027    * This method creates toggle button by the call to the method everyToggle(),
1028    * and then sets the button's action and tooltip text.
1029    * @param key name of the toggle button that will be created.
1030    * @return created toggle button.
1031    */

1032   protected JToggleButton createToggleButton(String JavaDoc key){
1033      JToggleButton Tb = everyToggle(key);
1034      Tb.setRequestFocusEnabled(false);
1035      Tb.setMargin(new Insets(1,1,1,1));
1036      String JavaDoc astr = getResourceString(key + "Action");
1037      if (astr == null) {
1038         astr = key;
1039      }
1040      Action a = getAction(astr);
1041      if (a != null) {
1042         Tb.setActionCommand(astr);
1043         Tb.addActionListener(toggleButtonListener);
1044      }
1045      else {
1046         Tb.setEnabled(false);
1047      }
1048      String JavaDoc tip = getResourceString(key + "Tooltip");
1049      if (tip != null) {
1050         Tb.setToolTipText(tip);
1051      }
1052      return Tb;
1053   }
1054   /*
1055    * Creating a ComboBoxes for fontfamily and for fontsize
1056    */

1057   /**
1058    * Creates JComboBox ComboBoxes for fontfamily and for fontsize based on the
1059    * key String, and assigns it to the corresponding field.<p>
1060    * Combobox items are read from property file using getResourceString method
1061    * @see #_fontsize
1062    * @see #_fontfamily
1063    * @param key name of category combobox is created for <br>valid values are contained in static Strings _fontfamily and _fontsize
1064    * @return newly created JComboBox (which is assigned to corresponding field, either comboFontFamilies or comboFontSizes)
1065    **/

1066   protected JComboBox createComboBoxes(String JavaDoc key){
1067// property file labels are somewhat different to key, so, key is now set to the proper value
1068
key =( key.equals( _fontfamily ))?( _family ):( _size );
1069// setting up variables for loop which would read values from property file
1070
int i = 1;
1071        String JavaDoc[] tmp = new String JavaDoc[ _maxComboItems ];
1072        for( String JavaDoc label; null !=( label = getResourceString( key + i + _label )); ++i )
1073            tmp[ i ]= label;
1074// at first we did not know how many values there are, now we do it is a value of i, we use it to
1075
// create properly sized itemlist
1076
String JavaDoc[] itemlist = new String JavaDoc[ i ];
1077        itemlist[ i - 1 ]= "";
1078// loop copies values from tmp array into itemlist
1079
while( --i > 0 )
1080            itemlist[ i - 1 ]= tmp[ i ];
1081// eventually we arrive at creating JComboBox adding an action listener and tooltip to it
1082
JComboBox cb = new JComboBox( itemlist );
1083
1084// inserting default values into combos
1085
// must define what to set (defFontFamily or defFontSize) and how to get
1086
// corresponding label to select(must take substring from Action label in
1087
// .property file to get defFontFamilyOrSize)
1088
String JavaDoc action;
1089      String JavaDoc selection;
1090      String JavaDoc defFamilyOrStyle;
1091      int substrstart;
1092      if (key.equals(_family)) {
1093         defFamilyOrStyle=defFontFamily;
1094         substrstart=12;
1095      }
1096      else {
1097         defFamilyOrStyle=defFontSize;
1098         substrstart=10;
1099      }
1100// loop through actions in property file to find right one
1101
for( i = 1; null !=( action = getResourceString( key + i + _action )); ++i ){
1102// must remove 'font-family-' from action string to get the family of the font
1103
action=action.substring(substrstart);
1104         if( defFamilyOrStyle.equals( action )){
1105// when found perform a selection
1106
selection = getResourceString( key + i + _label );
1107            cb.setSelectedItem(selection);
1108            break;
1109         }
1110      }
1111// enf of inserting default values in combos
1112

1113        cb.addActionListener( comboFontListener );
1114        tmp[ 1 ]= getResourceString( key + _tooltip );
1115        if( tmp[ 1 ]!= null )
1116            cb.setToolTipText( tmp[ 1 ]);
1117// this method does assign newly crated JComboBox to the proper field, the key should tell which one
1118
if( key.equals( _family ))
1119         return( comboFontFamilies = cb );
1120      else
1121         return( comboFontSizes = cb );
1122   }
1123   /**
1124    * Performs action of either changing font family or size.
1125    * Invoked by anonymous ActionListener assigned to both comboboxes.<p>
1126    * @param e ActionEvent to react upon
1127    */

1128   protected void comboFontActions(ActionEvent e){
1129   // selectedItem and key are crucial, so, set them first
1130
JComboBox source =( JComboBox )e.getSource();
1131        String JavaDoc selectedItem = source.getSelectedItem().toString();
1132        String JavaDoc key =( comboFontFamilies.equals( source ))?( _family ):( _size );
1133        Action act;
1134        String JavaDoc label;
1135// loop through labels in property file to find right one
1136
for( int i = 1; null !=( label = getResourceString( key + i + _label )); ++i ){
1137            if( selectedItem.equals( label )){
1138// when found perform a new action and
1139
act = getAction( getResourceString( key + i + _action ));
1140                act.actionPerformed( e );
1141// return focus to the editor
1142
editor.requestFocus();
1143            }
1144        }
1145    }
1146   /**
1147    * Creates a toolbar button. Sets button's icon, action and tooltip text.
1148    * @param key name of button to be created.
1149     * @return created button.
1150    */

1151   protected JButton createToolbarButton(String JavaDoc key) {
1152    URL JavaDoc url = getResource(key + "ImageTool");
1153      JButton b;
1154      try {
1155         b = new JButton(new ImageIcon(url)) {
1156            public float getAlignmentY() { return 0.5f; }
1157          };
1158       }
1159       catch (Exception JavaDoc e) {
1160        b = new JButton(key) {
1161            public float getAlignmentY() { return 0.5f; }
1162          };
1163       }
1164      b.setRequestFocusEnabled(false);
1165      b.setMargin(new Insets(1,1,1,1));
1166    String JavaDoc astr = getResourceString(key + "Action");
1167    if (astr == null) {
1168          astr = key;
1169    }
1170    Action a = getAction(astr);
1171      if (a != null) {
1172           b.setActionCommand(astr);
1173        b.addActionListener(a);
1174      }
1175      else {
1176       b.setEnabled(false);
1177      }
1178    String JavaDoc tip = getResourceString(key + "Tooltip");
1179    if (tip != null) {
1180          b.setToolTipText(tip);
1181      }
1182      return b;
1183   }
1184   /**
1185    * Performs action of changing font style.
1186    * Invoked by anonymous ActionListener assigned to all toggle buttons.
1187    * @param e ActionEvent to react upon
1188    */

1189   protected void toggleButtonActions(ActionEvent e) {
1190// find which button is pressed
1191
JToggleButton source=(JToggleButton)e.getSource();
1192      String JavaDoc key;
1193      if (source.equals(boldButton))
1194         key="bold";
1195      else if (source.equals(italicButton))
1196         key="italic";
1197      else
1198         key="underline";
1199// look in property file to find action
1200
String JavaDoc astr = getResourceString(key + "Action");
1201      if (astr == null) {
1202         astr = key;
1203      }
1204// when found perform a new action
1205
Action a = getAction(astr);
1206      if (a != null) {
1207         a.actionPerformed(e);
1208      }
1209// return focus to the editor
1210
editor.requestFocus();
1211   }
1212   /**
1213    * Method for testing purposes only
1214     * @param e ActionEvent to react upon
1215    **/

1216   public void testing(ActionEvent e){
1217      java.util.List JavaDoc listDoc=loading();
1218      Iterator iterDoc=listDoc.iterator();
1219      while(iterDoc.hasNext()) {
1220         Object JavaDoc nextDoc = iterDoc.next();
1221         java.util.List JavaDoc listParag=(java.util.List JavaDoc)nextDoc;
1222         Iterator iterParag=listParag.iterator();
1223         while(iterParag.hasNext()){
1224            Object JavaDoc nextAlign=iterParag.next();
1225            int align=Integer.parseInt(nextAlign.toString());
1226            Object JavaDoc nextSadrzaj=iterParag.next();
1227            System.out.println("Paragraf: Alignment="+align);
1228            java.util.List JavaDoc listSad=(java.util.List JavaDoc)nextSadrzaj;
1229            Iterator iterSad=listSad.iterator();
1230            while(iterSad.hasNext()){
1231               Object JavaDoc nextSad=iterSad.next();
1232               java.util.List JavaDoc listCon=(java.util.List JavaDoc)nextSad;
1233               Iterator iterCon=listCon.iterator();
1234               while(iterCon.hasNext()){
1235                  String JavaDoc Text=new String JavaDoc(iterCon.next().toString());
1236                  String JavaDoc FontFam=new String JavaDoc(iterCon.next().toString());
1237                  int FontSize=Integer.parseInt(iterCon.next().toString());
1238                  String JavaDoc bold=new String JavaDoc(iterCon.next().toString());
1239                  String JavaDoc italic=new String JavaDoc(iterCon.next().toString());
1240                  String JavaDoc underline=new String JavaDoc(iterCon.next().toString());
1241                  int Start=Integer.parseInt(iterCon.next().toString());
1242                  int End=Integer.parseInt(iterCon.next().toString());
1243                  System.out.println(" text: "+Text+"["+Start+","+End+"] "+FontFam+" "+FontSize+" "+"Bold="+bold+", Italic="+italic+", Underline="+underline);
1244               }
1245            }
1246         }
1247      }
1248   }
1249   /**
1250    * Method for loading a List called listDoc with all elements of editor.
1251    * Editor elements (written text elements) are:<br> *section-the main
1252    * root element which contains paragraphs<br> *paragraph-element that
1253    * contains alignment and character elements<br> *character-element
1254    * whose attributes are font family, font size and font style.
1255    * @return list that represents the writen text (document)
1256    **/

1257   public java.util.List JavaDoc loading(){
1258      StyledDocument document = getEditor().getStyledDocument();
1259      rootElements = document.getRootElements();
1260      //Debug
1261
Element sect=rootElements[0];
1262      int sectCnt=sect.getElementCount();
1263      //Debug
1264
Element parag=null;
1265      java.util.List JavaDoc listDoc = new ArrayList();
1266      //Loop for each paragraph
1267
for (int i=0;i<sectCnt;i++){
1268         java.util.List JavaDoc listPrg = new ArrayList();
1269         // 'i'th element of paragraph-content
1270
parag=sect.getElement(i);
1271         int paragCnt=parag.getElementCount();
1272         if (i==sectCnt-1 && sectCnt>1) paragCnt--;
1273         AttributeSet ParAS = parag.getAttributes();
1274         int intAlign=StyleConstants.getAlignment(ParAS);
1275         Element content=null;
1276         java.util.List JavaDoc listSad = new ArrayList();
1277         //Loop for each content of given paragraph
1278
for(int j=0;j<paragCnt;j++){
1279            java.util.List JavaDoc listCont = new ArrayList();
1280            content=parag.getElement(j);
1281            AttributeSet ParASL = content.getAttributes();
1282            String JavaDoc text;
1283            try{
1284                    text=document.getText(content.getStartOffset(),content.getEndOffset()-content.getStartOffset());
1285               String JavaDoc chngText="";
1286               for (int k=0; k<text.length(); k++) {
1287                  if (text.charAt(k)=='&')
1288                     chngText=chngText+"&amp;";
1289                  else if (text.charAt(k)=='<')
1290                     chngText=chngText+"&lt;";
1291                  else if (text.charAt(k)=='>')
1292                     chngText=chngText+"&gt;";
1293                  else
1294                     chngText=chngText+text.charAt(k);
1295               }
1296               text=chngText;
1297               listCont.add(text);
1298            }
1299            catch(BadLocationException e){
1300               listCont.add(new String JavaDoc());
1301               System.err.println("Exception "+e+" in range of given part of document");
1302            }
1303            listCont.add(new String JavaDoc(StyleConstants.getFontFamily(ParASL)));
1304            listCont.add(new Integer JavaDoc(StyleConstants.getFontSize(ParASL)));
1305            listCont.add(new Boolean JavaDoc(StyleConstants.isBold(ParASL)));
1306            listCont.add(new Boolean JavaDoc(StyleConstants.isItalic(ParASL)));
1307            listCont.add(new Boolean JavaDoc(StyleConstants.isUnderline(ParASL)));
1308            listCont.add(new Integer JavaDoc(content.getStartOffset()));
1309            listCont.add(new Integer JavaDoc(content.getEndOffset()));
1310            //Adding a element to a ArraysList-listSad
1311
listSad.add(listCont);
1312         }
1313         // Adding a elements to a ArraysList-listPrg so it will have the structure
1314
// similar like this: listPrg{Align,Sadrzaj}
1315
listPrg.add(new Integer JavaDoc(intAlign));
1316         listPrg.add(listSad);
1317         // Adding a elements to a ArraysList-listDoc
1318
listDoc.add(listPrg);
1319      }
1320      return listDoc;
1321   }
1322   /**
1323    * Method for creating string in a form of XSL FO file that represent a content of applet.
1324    * This method format applet's text, and transforms it into XSL FO form.
1325    * @return String formatted as XSL FO file
1326    **/

1327   public String JavaDoc FormatFO(){
1328      String JavaDoc fo=new String JavaDoc();
1329      String JavaDoc FOalign="start";
1330      String JavaDoc FObold="";
1331      String JavaDoc FOunder="";
1332      String JavaDoc FOital="";
1333      String JavaDoc Text=" ";
1334      String JavaDoc FontFam="sans-serif";
1335      int FontSize=12;
1336      java.util.List JavaDoc listDoc=loading();
1337      Iterator iterDoc=listDoc.iterator();
1338      while(iterDoc.hasNext()) {
1339         Object JavaDoc nextDoc = iterDoc.next();
1340         java.util.List JavaDoc listParag=(java.util.List JavaDoc)nextDoc;
1341         Iterator iterParag=listParag.iterator();
1342         while(iterParag.hasNext()){
1343            Object JavaDoc nextAlign=iterParag.next();
1344            int align=Integer.parseInt(nextAlign.toString());
1345            if (align==0)
1346               FOalign="start";
1347            else if(align==1)
1348               FOalign="center";
1349            else if(align==2)
1350               FOalign="end";
1351            Object JavaDoc nextSadrzaj=iterParag.next();
1352            fo+="<fo:block font-size=\"12pt\" font-family=\"sans-serif\" line-height=\""+defLineHeight+"pt\" space-after.optimum=\"3pt\" text-align=\""+FOalign+"\" white-space-collapse=\"false\" language=\""+defHyph+"\" hyphenate=\"true\">";
1353            java.util.List JavaDoc listSad=(java.util.List JavaDoc)nextSadrzaj;
1354            Iterator iterSad=listSad.iterator();
1355            while(iterSad.hasNext()){
1356               Object JavaDoc nextSad=iterSad.next();
1357               java.util.List JavaDoc listCon=(java.util.List JavaDoc)nextSad;
1358               Iterator iterCon=listCon.iterator();
1359               while(iterCon.hasNext()){
1360                  Text=new String JavaDoc(iterCon.next().toString());
1361                  if (Text.equals("\n")){
1362                     Text=" ";
1363                  }
1364                  FontFam=new String JavaDoc(iterCon.next().toString());
1365                  FontSize=Integer.parseInt(iterCon.next().toString());
1366                  String JavaDoc bold=new String JavaDoc(iterCon.next().toString());
1367                  String JavaDoc italic=new String JavaDoc(iterCon.next().toString());
1368                  String JavaDoc underline=new String JavaDoc(iterCon.next().toString());
1369                  int Start=Integer.parseInt(iterCon.next().toString());
1370                  int End=Integer.parseInt(iterCon.next().toString());
1371                  if (FontFam.equals("Monospaced"))
1372                     FontFam="Courier";
1373                  else if (FontFam.equals("SansSerif"))
1374                     FontFam="Helvetica";
1375                  else
1376                     FontFam="Times Roman";
1377                  if (bold.equals("true"))
1378                     FObold="font-weight=\"bold\" ";
1379                  else
1380                     FObold="";
1381                  if (italic.equals("true"))
1382                     FOital="font-style=\"italic\" ";
1383                  else
1384                     FOital="";
1385                  if (underline.equals("true"))
1386                     FOunder="text-decoration=\"underline\" ";
1387                  else
1388                     FOunder="";
1389                  fo+="<fo:inline font-family=\""+FontFam+"\" font-size=\""+FontSize+"pt\" "+FObold+FOital+FOunder+">"+Text;
1390                  fo+="</fo:inline>";
1391               }
1392            }
1393            fo+="</fo:block>";
1394         }
1395      }
1396   return fo;
1397   }
1398   /**
1399    * Behavior for curetEvent. With every caret movement, updates the
1400    * state and selection of toolbar buttons and combo boxes.
1401    * States and selections visualize the attribute settings of
1402    * the next character to be written at the current position of the caret.
1403    * @param e caret event to react upon.
1404    **/

1405   protected void caretChange(CaretEvent e){
1406      // if Enter or Back Space was pressed, return
1407
if (isEnterPressed==true) {
1408         return;
1409      }
1410      if (isBSValid==true) {
1411         return;
1412      }
1413      // if there is a selection, update combos and return
1414
int dot = e.getDot();
1415      int mark = e.getMark();
1416        if(dot != mark){
1417         if (comboFontFamilies != null) {
1418            comboFontFamilies.removeActionListener(comboFontListener);
1419            comboFontFamilies.setSelectedItem("");
1420            comboFontFamilies.addActionListener(comboFontListener);
1421         }
1422         if (comboFontSizes != null) {
1423            comboFontSizes.removeActionListener(comboFontListener);
1424            comboFontSizes.setSelectedItem("");
1425            comboFontSizes.addActionListener(comboFontListener);
1426         }
1427            return;
1428        }
1429
1430        StyledDocument theDocument = getEditor().getStyledDocument();
1431      // current paragraph and left and right char.
1432
Element prgel=theDocument.getParagraphElement(dot);
1433      Element leftel=theDocument.getCharacterElement(dot-1);
1434      Element rightel=theDocument.getCharacterElement(dot);
1435      Element curel;
1436
1437      // start and end of current paragraph
1438
int stof=prgel.getStartOffset();
1439      int enof=prgel.getEndOffset();
1440
1441      // always look to the left except at begining of non empty paragraph
1442
if (((dot==stof) && ((enof-stof)>1))){
1443         curel=rightel;
1444      }
1445      else {
1446         curel=leftel;
1447      }
1448
1449      //Attributes for character
1450
AttributeSet AttChar;
1451
1452      if ((dot==stof) && ((enof-stof)==1)) {
1453         AttChar=editor.getParagraphAttributes();
1454      }
1455      else {
1456         AttChar=curel.getAttributes();
1457      }
1458
1459      String JavaDoc ff=StyleConstants.getFontFamily(AttChar);
1460      int fs=StyleConstants.getFontSize(AttChar);
1461      boolean b=StyleConstants.isBold(AttChar);
1462      boolean i=StyleConstants.isItalic(AttChar);
1463      boolean u=StyleConstants.isUnderline(AttChar);
1464      // updating style buttons
1465
if ((boldButton != null) && (boldButton.isSelected()!=b)) {
1466         boldButton.removeActionListener(toggleButtonListener);
1467         boldButton.setSelected(b);
1468         boldButton.addActionListener(toggleButtonListener);
1469      }
1470      if ((italicButton != null) && (italicButton.isSelected()!=i)) {
1471         italicButton.removeActionListener(toggleButtonListener);
1472         italicButton.setSelected(i);
1473         italicButton.addActionListener(toggleButtonListener);
1474      }
1475      if ((underButton != null) && (underButton.isSelected()!=u)) {
1476         underButton.removeActionListener(toggleButtonListener);
1477         underButton.setSelected(u);
1478         underButton.addActionListener(toggleButtonListener);
1479      }
1480      // updating combo boxes selections (must remove ActionListener)
1481
String JavaDoc key;
1482      String JavaDoc action;
1483      String JavaDoc selection;
1484      if (comboFontFamilies != null) {
1485         comboFontFamilies.removeActionListener(comboFontListener);
1486         key = _family;
1487         // loop through actions in property file to find right one
1488
for( int j = 1; null !=( action = getResourceString( key + j + _action )); ++j ){
1489            // must remove 'font-family-' from action string to get the family of the font
1490
action=action.substring(12);
1491            if( ff.equals( action )){
1492               // when found perform a selection
1493
selection = getResourceString( key + j + _label );
1494                   comboFontFamilies.setSelectedItem(selection);
1495               break;
1496            }
1497         }
1498         comboFontFamilies.addActionListener(comboFontListener);
1499      }
1500      if (comboFontSizes != null) {
1501         comboFontSizes.removeActionListener(comboFontListener);
1502         key = _size;
1503         // loop through actions in property file to find right one
1504
for( int j = 1; null !=( action = getResourceString( key + j + _action )); ++j ){
1505            // must remove 'font-size-' from action string to get the size of the font
1506
action=action.substring(10);
1507            if( String.valueOf(fs).equals( action )){
1508               // when found perform a selection
1509
selection = getResourceString( key + j + _label );
1510                   comboFontSizes.setSelectedItem(selection);
1511               break;
1512            }
1513         }
1514         comboFontSizes.addActionListener(comboFontListener);
1515      }
1516      //Values for paragraph
1517
AttributeSet AttPar=getEditor().getParagraphAttributes();
1518      // updating alignment buttons
1519
int intAlign=StyleConstants.getAlignment(AttPar);
1520      switch (intAlign){
1521         case 0:
1522            if ((leftButton != null) && (leftButton.isSelected()!=true))
1523               leftButton.setSelected(true);
1524            break;
1525         case 1:
1526            if ((centerButton != null) && (centerButton.isSelected()!=true))
1527               centerButton.setSelected(true);
1528            break;
1529         case 2:
1530            if ((rightButton != null) && (rightButton.isSelected()!=true))
1531               rightButton.setSelected(true);
1532            break;
1533      }
1534   }
1535    /**Listens for mouse clicks and shows the popup menu when the right mouse buton is pressed.*/
1536    private final class PopMouseListener extends MouseAdapter {
1537      /** leaves all the job to super class */
1538        PopMouseListener() {
1539            super();
1540        }
1541      /** When right mouse button is pressed, builds up and shows the popup menu */
1542        public void mousePressed(MouseEvent e) {
1543            if ( (e.getModifiers() & InputEvent.BUTTON1_MASK) != 0 ) return;
1544            if (PopUp ==null) buildPop();
1545            PopUp.show(editor,e.getX(),e.getY());
1546        }
1547      /** Creates the popup menu */
1548      private void buildPop() {
1549            PopUp = new JPopupMenu();
1550            String JavaDoc[] itemKeys = {"cut","copy","copyExt","paste"};
1551            for (int i = 0; i < itemKeys.length; i++) {
1552               switch (itemKeys[i].charAt(0)) {
1553                   case '-' :
1554                       PopUp.addSeparator(); break;
1555                default:
1556                   JMenuItem mi = createMenuItem(itemKeys[i]);
1557                   PopUp.add(mi);
1558               }
1559           }
1560        }
1561    }
1562   /** Inner class for external copy **/
1563   class CopyExtAction extends AbstractAction{
1564
1565      public CopyExtAction() {
1566         super(copyExtAction);
1567      }
1568
1569      /* (non-Javadoc)
1570       * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
1571       */

1572      public void actionPerformed(ActionEvent e) {
1573         //editor.pickClipboardToUse();
1574
editor.copyExt();
1575      }
1576
1577   }
1578}
1579
1580
Popular Tags