Link to home
Start Free TrialLog in
Avatar of Batalf
BatalfFlag for United States of America

asked on

Replacing selected content in a JEditorPane

I'm trying to develop an web-publishing applet

First of all : It's been a while since last time I developed anything in Java. I'm daily working with HTML,Javascript and PHP and haven't have use for Java for a year, so please correct me if what I have done is wrong.

What I have done so far is :
1) Used a JEditorPane for the WYSIWYG-editor:
     final JEditorPane editor = new JEditorPane();
2) Set this editor to text/html and editable:
          editor.setEditable(true);
          editor.setContentType("text/html");

What I now want to do is this:
1) Get cursor-position from this EditorPane. I have tried using Caret posisjon = editor.getCaret(); but this isn't right because "behind the scenes", the EditorPane consist of html-tags, so the returned position is wrong.That's what's most tricky here.

2) Second question is how to retreve the selected part of the text in the JEditPane and replace it. Example: If the user press the "B"-button, the text "Batalf" will be replaced with "<b>Batalf</b>". The <b>'tag will of course not show, Batalf will just be written in a bold font.


Hopefully anyone of you could help me out.

Thanks in advance.

Batalf
ASKER CERTIFIED SOLUTION
Avatar of Ovi
Ovi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Batalf

ASKER

So the content of the

breakReader-function

will replace my actionListener for the bold-Button?(The actionListener for the bold button should get the cursor-position and insert a <b>-tag, and if some text is selected end the selection with a </b> tag.
Avatar of Ovi
Ovi

Actually this code is from a "paste" like function to paste html content into the editor. The code is from a java1.2 applet with a WYSWYG html editor, used without plug-in, in which the copy/paste from/to applet is maded via LiveConnect in communication with html code.

This is the complete class of my toolbar (old and unreviewed implementation):

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;

public class EditorToolBar extends JToolBar {
    JApplet opener;
    Preview prev;
    public EditorToolBar(JApplet opener) {
        this.opener=opener;
        createToolbar();
        prev = new Preview();
    }

This is the editor applet class; I suppose you could never compile them because of the many dependencies and many other classes used :

import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;
import com.sun.java.swing.text.html.*;
import netscape.javascript.JSObject;

public class Editor extends JApplet {
       
    public static DefaultStyledDocument doc;//original doc este de tipul StyledDocument
    public static JTextPane pane;
    public static JLabel statusInfo;
//    public static DocumentCaret crt;
    public static ButtonVector buttons;
   
    public static Image bird;
    public static Image cut;
    public static Image copy;
    public static Image paste;
    public static Image save;
    public static Image bold;
    public static Image italic;
    public static Image underline;
    public static Image left;
    public static Image right;
    public static Image center;
    public static Image justify;
    public static Image preview;
      public MediaTracker tracker;
      
      public static URL infoObj;
      public static URL time;
      public static URL location;
      public static URL numeric;
      public static URL bool;
      public static URL smartText;
      public static URL template;
      public static URL media;
    public static AppletContext context;
          
      public static boolean WYSIWYG=false;
      
    public void init() {        
        context = getAppletContext();
       
        buttons = new ButtonVector(20, 10);
        try {
            infoObj = new URL(getParameter("INFO")+"?NR1=8&NR2=5");
            time = new URL(getParameter("TIME")+"?NR1=8&NR2=5");
            location = new URL(getParameter("LOCATION")+"?NR1=8&NR2=5");
            numeric = new URL(getParameter("NUM")+"?NR1=8&NR2=5");
            bool = new URL(getParameter("BOOL")+"?NR1=8&NR2=5");
            smartText = new URL(getParameter("SMART")+"?NR1=8&NR2=5");
            template = new URL(getParameter("TEMPLATE")+"?NR1=8&NR2=5");
            media = new URL(getParameter("MEDIA")+"?NR1=8&NR2=5");
        }catch(MalformedURLException e) {
            System.out.println("Error at loading URL's from index.html");
        }
        tracker = new MediaTracker(this);
        cut = getImage(getCodeBase(), "cut.gif");        
        tracker.addImage(cut, 0);
        try {
            tracker.waitForID(0);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 0");
            return;
        }
        copy = getImage(getCodeBase(), "copy.gif");
        tracker.addImage(copy, 1);
        try {
            tracker.waitForID(1);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 1");
            return;
        }
        paste = getImage(getCodeBase(), "paste.gif");
        tracker.addImage(paste, 2);        
        try {
            tracker.waitForID(2);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 2");
            return;
        }
        bold = getImage(getCodeBase(), "bold.gif");
        tracker.addImage(bold, 3);
        try {
            tracker.waitForID(3);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 3");
            return;
        }
        italic = getImage(getCodeBase(), "italic.gif");
        tracker.addImage(italic, 4);
        try {
            tracker.waitForID(4);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 4");
            return;
        }
        underline = getImage(getCodeBase(), "underline.gif");
        tracker.addImage(underline, 5);
        try {
            tracker.waitForID(5);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 5");
            return;
        }
        left = getImage(getCodeBase(), "left.gif");
        tracker.addImage(left, 6);
        try {
            tracker.waitForID(6);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 6");
            return;
        }
        right = getImage(getCodeBase(), "right.gif");
        tracker.addImage(right, 7);
        try {
            tracker.waitForID(7);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 7");
            return;
        }
        center = getImage(getCodeBase(), "center.gif");
        tracker.addImage(center, 8);
        try {
            tracker.waitForID(8);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 8");
            return;
        }
        justify = getImage(getCodeBase(), "justify.gif");
        tracker.addImage(justify, 9);
        try {
            tracker.waitForID(9);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 9");
            return;
        }
        save = getImage(getCodeBase(), "save.gif");
        tracker.addImage(save, 10);
        try {
            tracker.waitForID(10);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 10");
            return;
        }
        bird = getImage(getCodeBase(), "middle.gif");
        tracker.addImage(bird, 11);
        try {
            tracker.waitForID(11);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 11");
            return;
        }
        preview = getImage(getCodeBase(), "preview.gif");
        tracker.addImage(preview, 12);
        try {
            tracker.waitForID(12);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 12");
            return;
        }
       
        boolean good = false;
        good = tracker.checkAll();
        good = tracker.isErrorAny();
        if (good)
            System.out.println("Error loading images !");
        else System.out.println("Images loaded !");        
       
        JRootPane rp = getRootPane();
        rp.putClientProperty("defeatSystemEventQueueCheck",Boolean.TRUE);

//        SetStyles set = new SetStyles();
       
        // Get ContentPane
        Container c = getContentPane();

        // Setup Status Message Area
        statusInfo = new JLabel();            
        c.add (statusInfo, BorderLayout.SOUTH);

        // Setup Text Pane
       
        doc = new DefaultStyledDocument();
        doc.addDocumentListener(new KeyEvents());
        pane = new JTextPane();
        pane.setDocument(doc);
        pane.addMouseListener(new MouseEvents());
  //      crt = new DocumentCaret();
  //      crt.install(pane);
         
        // Place in JScrollPane
        JScrollPane sp = new JScrollPane (pane);
        c.add(sp, BorderLayout.CENTER);
           
        // Toolbar
        EditorToolBar toolbar = new EditorToolBar(this);
        c.add("North",toolbar);
                    
        // Setup Menus
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar (menuBar);

        // Setup File Menu
        FileMenu file = new FileMenu ("File");
        file.setMnemonic('F');
        menuBar.add (file);

        // Setup Color Menu
        ColorMenu color = new ColorMenu("Color");
        color.setMnemonic('C');
        menuBar.add (color);

        // Setup Font Menu
        FontMenu myFont = new FontMenu("Font");
        myFont.setMnemonic('N');
        menuBar.add (myFont);

        // Setup Insert Menu
        ImageMenu insert = new ImageMenu("Image");
        menuBar.add (insert);       
       
        // Setup Object Menu
        ObjectMenu object = new ObjectMenu("Objects");
        object.setMnemonic('J');
        menuBar.add(object);        
    }
   
    public static String copyFromHTML() {
        String copy = "";
          String msg[]=null;
          JSObject win=null;
          try {
                msg = new String[1];
                msg[0] = new String("");
                win = JSObject.getWindow(context.getApplet("Editor"));
          } catch (Exception e1) {
                System.out.println("Exceptie la FROM HTML : "+e1.toString());
          }
          try {
              copy = (win.call("getClip",msg)).toString();
          } catch (Exception e2) {
                System.out.println("Exceptie1 la FROM HTML : "+e2.toString());
          }        
        return copy;
    }
   
    public static void pasteToHTML(String text) {
          String msg[]=null;
          JSObject win=null;
          try {
                msg = new String[1];
                msg[0] = text;
                win = JSObject.getWindow(context.getApplet("Editor"));
          } catch (Exception e1) {
                System.out.println("Exceptie la TO HTML : "+e1.toString());
          }
          try {
              win.call("setClip",msg);
          } catch (Exception e2) {
                System.out.println("Exceptie1 la TO HTML : "+e2.toString());
          }        
    }
}

Actually my implementation of the bold action as you can see in the toolbar class is a StyledEditorKit.BoldAction.
   
    private Component createToolbar() {
          String[] toolKeys = tokenize("save - copy paste - bold italic underline - left center right justify - - - preview");
          for (int i = 0; i < toolKeys.length; i++) {
                if (toolKeys[i].equals("-")) {
                this.add(Box.createHorizontalStrut(5));
                } else {
                this.add(createTool(toolKeys[i]));
                }
          }
          this.add(Box.createHorizontalGlue());
          return this;
    }
       
    protected String[] tokenize(String input) {
                Vector v = new Vector(10, 10);
                StringTokenizer t = new StringTokenizer(input);
                String cmd[];
                
                while (t.hasMoreTokens())
                      v.addElement(t.nextToken());
                cmd = new String[v.size()];
                for (int i = 0; i < cmd.length; i++)
                      cmd[i] = (String) v.elementAt(i);
                return cmd;
    }
       
    protected Component createTool(String key) {
                return createToolbarButton(key);
    }
     
    protected JButton createToolbarButton(String key) {    
        Image img = null;
       
        for(int i = 0; i<11; i++) {
            if(key.equalsIgnoreCase("save")) img = Editor.save;
            else
//            if(key.equalsIgnoreCase("cut")) img = Editor.cut;
//            else
            if(key.equalsIgnoreCase("copy")) img = Editor.copy;
            else
            if(key.equalsIgnoreCase("paste")) img = Editor.paste;
            else
            if(key.equalsIgnoreCase("bold")) img = Editor.bold;
            else
            if(key.equalsIgnoreCase("italic")) img = Editor.italic;
            else
            if(key.equalsIgnoreCase("underline")) img = Editor.underline;
            else
            if(key.equalsIgnoreCase("center")) img = Editor.center;
            else
            if(key.equalsIgnoreCase("left")) img = Editor.left;
            else
            if(key.equalsIgnoreCase("right")) img = Editor.right;
            else
            if(key.equalsIgnoreCase("justify")) img = Editor.justify;
            else
            if(key.equalsIgnoreCase("preview")) img = Editor.preview;            
        }
        JButton b = new JButton(new ImageIcon(img)) {
                  public float getAlignmentY() { return 0.5f; }
                    };
          b.setRequestFocusEnabled(false);
          b.setMargin(new Insets(1,1,1,1));
          
            if(key.equalsIgnoreCase("save")) {
                        b.setActionCommand("doSaveCommand()");
                        String tip = "Save";
                        b.setToolTipText(tip);
                      b.addActionListener(new ActionListener() {
                    public void actionPerformed (ActionEvent e) {
                        FileMenu.doSaveCommand();
                    }
                          });
            }
/*            else if(key.equalsIgnoreCase("cut")) {
                  b.setActionCommand("cut-to-clipboard");
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          Editor.pane.cut();
                      }
                      });
                  String tip = "Cut - Ctrl+X";
                  b.setToolTipText(tip);
            }*/
            else if(key.equalsIgnoreCase("copy")) {
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          int pos = 0;
                          pos = Editor.pane.getCaretPosition();
                          String text = Editor.copyFromHTML();
                          if(text!=null) {
                              try {
                                  Editor.doc.insertString(pos,text,null);
                              }catch(BadLocationException ex) {
                                  System.out.println(ex.toString());
                              }
                          }
                      }
                      });
                  String tip = "Paste from HTML";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("paste")) {
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                    String selectedText = Editor.pane.getSelectedText();
                    System.out.println("Selected text : "+selectedText);
                    if(selectedText != null) Editor.pasteToHTML(selectedText);
                      }
                      });
                  String tip = "Paste to HTML";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("bold")) {
                  b.setActionCommand("new StyledEditorKit.BoldAction ()");
                b.addActionListener(new StyledEditorKit.BoldAction ());
                  String tip = "Bold";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("italic")) {
                  b.setActionCommand("new StyledEditorKit.ItalicAction ()");
                  b.addActionListener(new StyledEditorKit.ItalicAction ());
                  String tip = "Italic";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("underline")) {
                  b.setActionCommand("new StyledEditorKit.UnderlineAction ()");
                  b.addActionListener(new StyledEditorKit.UnderlineAction ());
                  String tip = "Underline";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("left")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Left Action\", 0)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Left Action", 0));                                    
                  String tip = "Left Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("center")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Center Action\", 1)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Center Action", 1));                                    
                  String tip = "Center Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("right")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Right Action\", 2)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Right Action", 2));                                    
                  String tip = "Right Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("justify")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Justify Action\", 3)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Justify Action", 3));                                    
                  String tip = "Justify";
                  b.setToolTipText(tip);
            }       
            else if(key.equalsIgnoreCase("preview")) {
                  b.addActionListener (new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          Editor.WYSIWYG = ! Editor.WYSIWYG;
                          if(!Editor.buttons. isEmpty())
                        prev.makePreview();
                 }
                      });                                    
                  String tip = "Preview";
                  b.setToolTipText(tip);
            }       
          return b;
    }
   
}
Sorry for the comment I didn't paste'it correctly. I will do'it again :

import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;
import com.sun.java.swing.text.html.*;
import netscape.javascript.JSObject;

public class Editor extends JApplet {
       
    public static DefaultStyledDocument doc;//original doc este de tipul StyledDocument
    public static JTextPane pane;
    public static JLabel statusInfo;
//    public static DocumentCaret crt;
    public static ButtonVector buttons;
   
    public static Image bird;
    public static Image cut;
    public static Image copy;
    public static Image paste;
    public static Image save;
    public static Image bold;
    public static Image italic;
    public static Image underline;
    public static Image left;
    public static Image right;
    public static Image center;
    public static Image justify;
    public static Image preview;
      public MediaTracker tracker;
      
      public static URL infoObj;
      public static URL time;
      public static URL location;
      public static URL numeric;
      public static URL bool;
      public static URL smartText;
      public static URL template;
      public static URL media;
    public static AppletContext context;
          
      public static boolean WYSIWYG=false;
      
    public void init() {        
        context = getAppletContext();
       
        buttons = new ButtonVector(20, 10);
        try {
            infoObj = new URL(getParameter("INFO")+"?NR1=8&NR2=5");
            time = new URL(getParameter("TIME")+"?NR1=8&NR2=5");
            location = new URL(getParameter("LOCATION")+"?NR1=8&NR2=5");
            numeric = new URL(getParameter("NUM")+"?NR1=8&NR2=5");
            bool = new URL(getParameter("BOOL")+"?NR1=8&NR2=5");
            smartText = new URL(getParameter("SMART")+"?NR1=8&NR2=5");
            template = new URL(getParameter("TEMPLATE")+"?NR1=8&NR2=5");
            media = new URL(getParameter("MEDIA")+"?NR1=8&NR2=5");
        }catch(MalformedURLException e) {
            System.out.println("Error at loading URL's from index.html");
        }
        tracker = new MediaTracker(this);
        cut = getImage(getCodeBase(), "cut.gif");        
        tracker.addImage(cut, 0);
        try {
            tracker.waitForID(0);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 0");
            return;
        }
        copy = getImage(getCodeBase(), "copy.gif");
        tracker.addImage(copy, 1);
        try {
            tracker.waitForID(1);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 1");
            return;
        }
        paste = getImage(getCodeBase(), "paste.gif");
        tracker.addImage(paste, 2);        
        try {
            tracker.waitForID(2);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 2");
            return;
        }
        bold = getImage(getCodeBase(), "bold.gif");
        tracker.addImage(bold, 3);
        try {
            tracker.waitForID(3);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 3");
            return;
        }
        italic = getImage(getCodeBase(), "italic.gif");
        tracker.addImage(italic, 4);
        try {
            tracker.waitForID(4);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 4");
            return;
        }
        underline = getImage(getCodeBase(), "underline.gif");
        tracker.addImage(underline, 5);
        try {
            tracker.waitForID(5);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 5");
            return;
        }
        left = getImage(getCodeBase(), "left.gif");
        tracker.addImage(left, 6);
        try {
            tracker.waitForID(6);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 6");
            return;
        }
        right = getImage(getCodeBase(), "right.gif");
        tracker.addImage(right, 7);
        try {
            tracker.waitForID(7);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 7");
            return;
        }
        center = getImage(getCodeBase(), "center.gif");
        tracker.addImage(center, 8);
        try {
            tracker.waitForID(8);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 8");
            return;
        }
        justify = getImage(getCodeBase(), "justify.gif");
        tracker.addImage(justify, 9);
        try {
            tracker.waitForID(9);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 9");
            return;
        }
        save = getImage(getCodeBase(), "save.gif");
        tracker.addImage(save, 10);
        try {
            tracker.waitForID(10);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 10");
            return;
        }
        bird = getImage(getCodeBase(), "middle.gif");
        tracker.addImage(bird, 11);
        try {
            tracker.waitForID(11);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 11");
            return;
        }
        preview = getImage(getCodeBase(), "preview.gif");
        tracker.addImage(preview, 12);
        try {
            tracker.waitForID(12);
        } catch(Exception x) {
            System.out.println("Eroare la tracker 12");
            return;
        }
       
        boolean good = false;
        good = tracker.checkAll();
        good = tracker.isErrorAny();
        if (good)
            System.out.println("Error loading images !");
        else System.out.println("Images loaded !");        
       
        JRootPane rp = getRootPane();
        rp.putClientProperty("defeatSystemEventQueueCheck",Boolean.TRUE);

//        SetStyles set = new SetStyles();
       
        // Get ContentPane
        Container c = getContentPane();

        // Setup Status Message Area
        statusInfo = new JLabel();            
        c.add (statusInfo, BorderLayout.SOUTH);

        // Setup Text Pane
       
        doc = new DefaultStyledDocument();
        doc.addDocumentListener(new KeyEvents());
        pane = new JTextPane();
        pane.setDocument(doc);
        pane.addMouseListener(new MouseEvents());
  //      crt = new DocumentCaret();
  //      crt.install(pane);
         
        // Place in JScrollPane
        JScrollPane sp = new JScrollPane (pane);
        c.add(sp, BorderLayout.CENTER);
           
        // Toolbar
        EditorToolBar toolbar = new EditorToolBar(this);
        c.add("North",toolbar);
                    
        // Setup Menus
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar (menuBar);

        // Setup File Menu
        FileMenu file = new FileMenu ("File");
        file.setMnemonic('F');
        menuBar.add (file);

        // Setup Color Menu
        ColorMenu color = new ColorMenu("Color");
        color.setMnemonic('C');
        menuBar.add (color);

        // Setup Font Menu
        FontMenu myFont = new FontMenu("Font");
        myFont.setMnemonic('N');
        menuBar.add (myFont);

        // Setup Insert Menu
        ImageMenu insert = new ImageMenu("Image");
        menuBar.add (insert);       
       
        // Setup Object Menu
        ObjectMenu object = new ObjectMenu("Objects");
        object.setMnemonic('J');
        menuBar.add(object);        
    }
   
    public static String copyFromHTML() {
        String copy = "";
          String msg[]=null;
          JSObject win=null;
          try {
                msg = new String[1];
                msg[0] = new String("");
                win = JSObject.getWindow(context.getApplet("Editor"));
          } catch (Exception e1) {
                System.out.println("Exceptie la FROM HTML : "+e1.toString());
          }
          try {
              copy = (win.call("getClip",msg)).toString();
          } catch (Exception e2) {
                System.out.println("Exceptie1 la FROM HTML : "+e2.toString());
          }        
        return copy;
    }
   
    public static void pasteToHTML(String text) {
          String msg[]=null;
          JSObject win=null;
          try {
                msg = new String[1];
                msg[0] = text;
                win = JSObject.getWindow(context.getApplet("Editor"));
          } catch (Exception e1) {
                System.out.println("Exceptie la TO HTML : "+e1.toString());
          }
          try {
              win.call("setClip",msg);
          } catch (Exception e2) {
                System.out.println("Exceptie1 la TO HTML : "+e2.toString());
          }        
    }
}




---------------------------------------------------------


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import com.sun.java.swing.*;
import com.sun.java.swing.text.*;

public class EditorToolBar extends JToolBar {
    JApplet opener;
    Preview prev;
    public EditorToolBar(JApplet opener) {
        this.opener=opener;
        createToolbar();
        prev = new Preview();
    }
   
    private Component createToolbar() {
          String[] toolKeys = tokenize("save - copy paste - bold italic underline - left center right justify - - - preview");
          for (int i = 0; i < toolKeys.length; i++) {
                if (toolKeys[i].equals("-")) {
                this.add(Box.createHorizontalStrut(5));
                } else {
                this.add(createTool(toolKeys[i]));
                }
          }
          this.add(Box.createHorizontalGlue());
          return this;
    }
       
    protected String[] tokenize(String input) {
                Vector v = new Vector(10, 10);
                StringTokenizer t = new StringTokenizer(input);
                String cmd[];
                
                while (t.hasMoreTokens())
                      v.addElement(t.nextToken());
                cmd = new String[v.size()];
                for (int i = 0; i < cmd.length; i++)
                      cmd[i] = (String) v.elementAt(i);
                return cmd;
    }
       
    protected Component createTool(String key) {
                return createToolbarButton(key);
    }
     
    protected JButton createToolbarButton(String key) {    
        Image img = null;
       
        for(int i = 0; i<11; i++) {
            if(key.equalsIgnoreCase("save")) img = Editor.save;
            else
//            if(key.equalsIgnoreCase("cut")) img = Editor.cut;
//            else
            if(key.equalsIgnoreCase("copy")) img = Editor.copy;
            else
            if(key.equalsIgnoreCase("paste")) img = Editor.paste;
            else
            if(key.equalsIgnoreCase("bold")) img = Editor.bold;
            else
            if(key.equalsIgnoreCase("italic")) img = Editor.italic;
            else
            if(key.equalsIgnoreCase("underline")) img = Editor.underline;
            else
            if(key.equalsIgnoreCase("center")) img = Editor.center;
            else
            if(key.equalsIgnoreCase("left")) img = Editor.left;
            else
            if(key.equalsIgnoreCase("right")) img = Editor.right;
            else
            if(key.equalsIgnoreCase("justify")) img = Editor.justify;
            else
            if(key.equalsIgnoreCase("preview")) img = Editor.preview;            
        }
        JButton b = new JButton(new ImageIcon(img)) {
                  public float getAlignmentY() { return 0.5f; }
                    };
          b.setRequestFocusEnabled(false);
          b.setMargin(new Insets(1,1,1,1));
          
            if(key.equalsIgnoreCase("save")) {
                        b.setActionCommand("doSaveCommand()");
                        String tip = "Save";
                        b.setToolTipText(tip);
                      b.addActionListener(new ActionListener() {
                    public void actionPerformed (ActionEvent e) {
                        FileMenu.doSaveCommand();
                    }
                          });
            }
/*            else if(key.equalsIgnoreCase("cut")) {
                  b.setActionCommand("cut-to-clipboard");
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          Editor.pane.cut();
                      }
                      });
                  String tip = "Cut - Ctrl+X";
                  b.setToolTipText(tip);
            }*/
            else if(key.equalsIgnoreCase("copy")) {
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          int pos = 0;
                          pos = Editor.pane.getCaretPosition();
                          String text = Editor.copyFromHTML();
                          if(text!=null) {
                              try {
                                  Editor.doc.insertString(pos,text,null);
                              }catch(BadLocationException ex) {
                                  System.out.println(ex.toString());
                              }
                          }
                      }
                      });
                  String tip = "Paste from HTML";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("paste")) {
                  b.addActionListener(new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                    String selectedText = Editor.pane.getSelectedText();
                    System.out.println("Selected text : "+selectedText);
                    if(selectedText != null) Editor.pasteToHTML(selectedText);
                      }
                      });
                  String tip = "Paste to HTML";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("bold")) {
                  b.setActionCommand("new StyledEditorKit.BoldAction ()");
                b.addActionListener(new StyledEditorKit.BoldAction ());
                  String tip = "Bold";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("italic")) {
                  b.setActionCommand("new StyledEditorKit.ItalicAction ()");
                  b.addActionListener(new StyledEditorKit.ItalicAction ());
                  String tip = "Italic";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("underline")) {
                  b.setActionCommand("new StyledEditorKit.UnderlineAction ()");
                  b.addActionListener(new StyledEditorKit.UnderlineAction ());
                  String tip = "Underline";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("left")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Left Action\", 0)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Left Action", 0));                                    
                  String tip = "Left Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("center")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Center Action\", 1)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Center Action", 1));                                    
                  String tip = "Center Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("right")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Right Action\", 2)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Right Action", 2));                                    
                  String tip = "Right Justify";
                  b.setToolTipText(tip);
            }
            else if(key.equalsIgnoreCase("justify")) {
                  b.setActionCommand ("new StyledEditorKit.AlignmentAction (\"Justify Action\", 3)");                                    
                  b.addActionListener (new StyledEditorKit.AlignmentAction ("Justify Action", 3));                                    
                  String tip = "Justify";
                  b.setToolTipText(tip);
            }       
            else if(key.equalsIgnoreCase("preview")) {
                  b.addActionListener (new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                          Editor.WYSIWYG = ! Editor.WYSIWYG;
                          if(!Editor.buttons. isEmpty())
                        prev.makePreview();
                 }
                      });                                    
                  String tip = "Preview";
                  b.setToolTipText(tip);
            }       
          return b;
    }
   
}