MultiPaged Editor Kit

I am attempting to create a multipaged editor kit. Up to this point, I have been able to simulate the behavior of multiple pages, by changing the offsets of the paragraph views so that they are off of the current screen when its contents would span the current page. However, when a paragraph view has mutliple lines, all of the lines are offset to the new page. I am looking for a way to be able to split up these lines so that one line may be on one page with an offset that breaks that page. I realize that the paragraph view has the lines already broken up in row views, but I am unable to determine how I can adjust their offsets.
I hope my problem is clear,
thank you,

I tried to remove a large amount of unnecessary code that was in it. Hopefully it does not throw any errors for you. There are two different files.
MyPagedEditorKit.java
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Shape;
import java.util.Vector;
import javax.swing.SizeRequirements;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.Position;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
public class MyPagedEditorKit extends StyledEditorKit {
     private MyViewFactory factory;
     public int pageHeight = 600;
     public int[] otherOffsets;
     public int childCounter=0;
     public int pageNumber=0;
     int totalOffset=0;
     public Insets pageMargins=new Insets(5,5,5,5);
     public static int DRAW_PAGE_INSET=5;
     private Object[] clipBoard;
     public class MyViewFactory implements ViewFactory {
          /** The default factory to use when we don't care what the view is **/
          private ViewFactory defaultFactory;
          private View myView;
           * Constructs a new MyViewFactory
           * @param def The default factory to use when this factory doesn't care
          public MyViewFactory(ViewFactory def) {
               defaultFactory = def;
           * @see javax.swing.text.ViewFactory#create(javax.swing.text.Element)
          public View create(Element elem) {
               String kind = elem.getName();
               if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
               } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                     myView = new ParagraphView(elem);
               } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    myView = new PagedBoxView(elem, View.Y_AXIS);
               } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
               } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
               } else {
                    myView = defaultFactory.create(elem);               
               return myView;
          protected View getView(){
               return myView;
     public StyledPagedEditorKit() {
          super();
          factory = new MyViewFactory(super.getViewFactory());
      * @see javax.swing.text.EditorKit#getViewFactory()
     public ViewFactory getViewFactory() {
          return factory;
     public View getView(){
          return factory.getView();
     public class PagedBoxView extends BoxView {
           * @param elem
           * @param axis
          public PagedBoxView(Element elem, int axis) {
               super(elem, axis);
               pageBounds = new Rectangle(0,0,300,600); // goofy default
//          public int pageHeight = 600;
          public int pageWidth = 300;
          Vector pageLocs = null;
          int pageNumber=0;
           * @see javax.swing.text.View#paint(java.awt.Graphics, java.awt.Shape)
          public void paint(Graphics g, Shape a) {
               super.paint(g,a);
          public void setHeight(int height){
               pageHeight = height;
          public int getHeight(){
               return pageHeight;
          public void setWidth(int width){
               pageWidth = width;
          public void setPageLocs(Vector pL){
               pageLocs = pL;
          public int getWidth(){
               return pageWidth;
          protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
               super.layoutMajorAxis(targetSpan, axis, offsets, spans);
               totalOffset=0;
               int n=offsets.length;
               pageNumber=1;
               int totalSpan = 0;
               //otherOffsets=new int[getViewCount()];
               for (int i = 0; i < getViewCount(); i++) {
                    View ithView = getView(i);
                    offsets=totalSpan;
                    if(pageNumber*pageHeight < offsets[i]+spans[i]+5){
                         totalSpan=pageNumber*pageHeight+(pageNumber==0?0:0);
                         offsets[i]=totalSpan;
                         pageNumber++;
                    totalSpan+=spans[i];
               otherOffsets=offsets;
               childCounter=0;
               for (int i = 0; i < getViewCount(); i++){
                    View ithView = getView(i);
                    for (int j = 0; j < ithView.getViewCount(); j++){
                         View jthView = getView(j);
                         for (int k = 0; k < jthView.getViewCount(); k++){
                              View kthView = getView(k);
          public float getPreferredSpan(int axis) {
               float span = 0;
               if (axis == View.X_AXIS) {
                    span = pageWidth;
               } else {
                    span = pageHeight * pageNumber;
               return span;
          public float getMinimumSpan(int axis) {
               return getPreferredSpan(axis);
          /** Shape of the pageBoundary to clip to **/
          Shape pageBounds;
          * Sets the current page boundary to clip to
          * @param s Shape representing the clip boundary (probably a Rectangle)
          public void setCurrentPageBounds(Shape s) {
               System.out.println("New page bounds: " + s);
               pageBounds = s;
Demo.java
* TextComponentDemo.java is a 1.4 application that requires
* one additional file:
*   DocumentSizeFilter
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.NavigationFilter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.Position.Bias;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;
public class Demo extends JFrame {
    JTextPane textPane;
    JScrollPane scrollPane;
    MyStyledDocument doc;
    static final int MAX_CHARACTERS = 300;
    JTextArea changeLog;
    String newline = "\n";
    HashMap actions;
    MyStyledDocument doc2 = new MyStyledDocument();
    boolean blockpage = false;
    boolean startingComponent = true;
    public TextComponentDemo() {
        super("");
        //Create the text pane and configure it.
        textPane = new JTextPane();
        textPane.getCaret().addChangeListener(new ChangeListener(){
             public void stateChanged(ChangeEvent e){
                  System.out.println("StateChanged");
                  gotoPage();
        textPane.setAutoscrolls(false);
        textPane.setContentType("text/rtf");
        textPane.setEditorKit(new StyledPagedEditorKit());
        textPane.setSelectionColor(Color.GRAY);
        textPane.setPreferredSize(new Dimension(200,600));
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5,5,5,5));
        doc = new MyStyledDocument(textPane);
        textPane.setStyledDocument(doc);
        Runnable r = new Runnable() {
             public void run() {
                  currentRect = textPane.getBounds();
                  pageY = currentRect.y;
                  pageX = currentRect.x;
                  System.out.println("Initial rect: " + currentRect);
                    pageLocs.add(currentRect);
          SwingUtilities.invokeLater(r);
        scrollPane = new JScrollPane(textPane);
        this.getContentPane().add(scrollPane);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        //Create the text area for the status log and configure it.
        changeLog = new JTextArea(5, 30);
        changeLog.setEditable(false);
        JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
        //Create a split pane for the change log and the text area.
        JSplitPane splitPane = new JSplitPane(
                                       JSplitPane.VERTICAL_SPLIT,
                                       scrollPane, scrollPaneForLog);
        splitPane.setOneTouchExpandable(true);
        //Create the status area.
        JPanel statusPane = new JPanel(new GridLayout(1, 1));
        CaretListenerLabel caretListenerLabel =
                new CaretListenerLabel("Caret Status");
        statusPane.add(caretListenerLabel);
        //Add the components.
        getContentPane().add(splitPane, BorderLayout.CENTER);
        getContentPane().add(statusPane, BorderLayout.PAGE_END);
        //Set up the menu bar.
        createActionTable(textPane);
        JMenu editMenu = createEditMenu();
        JMenu styleMenu = createStyleMenu();
        JMenuBar mb = new JMenuBar();
        mb.add(editMenu);
        mb.add(styleMenu);
        setJMenuBar(mb);
        //Add some key bindings.
        addBindings();
        //Start watching for undoable edits and caret changes.
        doc.addUndoableEditListener(undoer);
        //Put the initial text into the text pane.
        initDocument();
    //This listens for and reports caret movements.
    protected class CaretListenerLabel extends JLabel
                                       implements CaretListener {
        public CaretListenerLabel(String label) {
            super(label);
        //Might not be invoked from the event dispatching thread.
        public void caretUpdate(CaretEvent e) {
            displaySelectionInfo(e.getDot(), e.getMark());
            try{
            System.out.println("caretUpdate: "+ textPane.modelToView(e.getMark()));
        }catch(BadLocationException ef){
        //This method can be invoked from any thread.  It
        //invokes the setText and modelToView methods, which
        //must run in the event dispatching thread. We use
        //invokeLater to schedule the code for execution
        //in the event dispatching thread.
        protected void displaySelectionInfo(final int dot,
                                            final int mark) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    if (dot == mark) {  // no selection
                        try {             
                            Rectangle caretCoords = textPane.modelToView(dot);
                            //Convert it to view coordinates.
                            setText("caret: text position: " + dot
                                    + ", view location = ["
                                    + caretCoords.x + ", "
                                    + caretCoords.y + "]"
                                    + newline);
                        } catch (BadLocationException ble) {
                            setText("caret: text position: " + dot + newline);
                    } else if (dot < mark) {
                        setText("selection from: " + dot
                                + " to " + mark + newline);
                    } else {
                        setText("selection from: " + mark
                                + " to " + dot + newline);
    private void printViews(View v, int depth) {
         int cnt = v.getViewCount();
         System.out.println(depth + " , " + v.getClass());
         for(int ix=0;ix<cnt;ix++) {
              View v2 = v.getView(ix);
              printViews(v2,depth+1);
    public void gotoPage(){
         int caretPos = textPane.getCaretPosition();
         try {
              Rectangle caretPage = textPane.modelToView(caretPos);
                   if (!startingComponent && caretPage != null){
                        currentPage=(caretPage.height + caretPage.y)/textPane.getVisibleRect().height+1;
                        System.out.println("CurrentPage: "+currentPage);
                        textPane.scrollRectToVisible(new Rectangle(caretPage.x,(currentPage-1)*textPane.getVisibleRect().height,textPane.getVisibleRect().width,textPane.getVisibleRect().height));
                   } else
                        startingComponent=false;
         }catch(BadLocationException e){}
      * Returns an image array representing the current text editor
      * images are cropped to fit within printed margins.
      * @param top Value of top margin
      * @param bottom Value of bottom margin
      * @param Image[] Length >= 1
     public Image[] getPrintableImages(double top, double bottom)
          setPageLocs();
          Dimension d = textPane.getSize();
          int DPI = 72; // default dots per inch
          int numPages = pageLocs.size();//Number or Pages
          Image[] ret = new Image[numPages];
          // hide caret and selection so it doesn't show up on printout
          textPane.getCaret().setVisible(false);
          textPane.getCaret().setSelectionVisible(false);
          // get the image we will crop to get the correct pieces.
          Image i = textPane.createImage(d.width,d.height);
          Graphics g = i.getGraphics();
          //Insets in = textPane.getInsets();
          //textPane.setMargin(new Insets(0,0,0,0) ); // get rid of the top margin
          textPane.paint(g);
          //textPane.setMargin(in); // restore margins
          g.dispose();
          Rectangle printableArea;
          for(int ix=0;ix<numPages;ix++) // go through the larger image and pull out page sized sections of it.
               printableArea = (Rectangle)pageLocs.get(ix);
               FilteredImageSource fis = new FilteredImageSource(i.getSource(),new CropImageFilter(printableArea.x,printableArea.y,printableArea.width,printableArea.height) );
               ret[ix] = textPane.createImage(fis);
          if(textPane.isEnabled() )
              textPane.getCaret().setVisible(true);
              textPane.getCaret().setSelectionVisible(false);
          /*BMPFile saveIt = new BMPFile();
          for(int ix = 0; ix<ret.length; ix++){
               printableArea = (Rectangle)pageLocs.get(ix);
               saveIt.saveBitmap("file" + ix+".bmp",ret[ix],printableArea.width,printableArea.height);
          return ret;
     public void setPageLocs(){
          //clear the pageLocs vector of previous page information
          pageLocs.removeAllElements();
          Rectangle newPage=null;
          try{
               Insets margins = textPane.getInsets();
               int currentHeight = 0;
               int currentY=-1;
               currentPage = 0;
               Rectangle prevPage= new Rectangle(0,margins.top,0,0);
               int heightCounter=0;
               int margin = 0;
               for(int i = 0; i <= doc.getLength(); i++){//Loops through every character position to determine the number of pages and their size.
                    newPage = textPane.modelToView(i);
                    if (newPage == null)
                         return;
                    if (newPage.y>currentY){//Check to see if this is a new line
                         currentY = newPage.y;//Updates line counter to the new line location.
                         if (currentHeight + newPage.height > textPane.getVisibleRect().height){//Checks to see if the current measured page height is larger than the viewable window height.
                              prevPage = new Rectangle(prevPage.x,pageLocs.size()*textPane.getVisibleRect().height,textPane.getVisibleRect().width,textPane.getVisibleRect().height);
                              pageLocs.add(prevPage);
                              currentHeight = 0;
                              margin+=5;
                         currentHeight+= newPage.height;
                    if(textPane.getCaretPosition()==i){
                         currentPage = pageLocs.size();
                         System.out.println("currentPage: "+currentPage);
               prevPage = new Rectangle(prevPage.x,pageLocs.size()*textPane.getVisibleRect().height,textPane.getVisibleRect().width,textPane.getVisibleRect().height);
               System.out.println("prevPage: "+prevPage);
               pageLocs.add(prevPage);
          } catch(BadLocationException e){
               System.out.println(e);
    Vector pageLocs = new Vector(10);
    Rectangle currentRect;
    int currentPage = 0;
    private int pageY = 0;
    private int pageX = 0;
    //This one listens for edits that can be undone.
    //And this one listens for any changes to the document.
    protected class MyDocumentListener
                    implements DocumentListener {
        public void insertUpdate(DocumentEvent e) {
            displayEditInfo(e);
        public void removeUpdate(DocumentEvent e) {
            displayEditInfo(e);
        public void changedUpdate(DocumentEvent e) {
            displayEditInfo(e);
        private void displayEditInfo(DocumentEvent e) {             
            Document document = (Document)e.getDocument();
            int changeLength = e.getLength();
            changeLog.append(e.getType().toString() + ": " +
                changeLength + " character" +
                ((changeLength == 1) ? ". " : "s. ") +
                " Text length = " + document.getLength() +
                "." + newline);
    //Add a couple of emacs key bindings for navigation.
    protected void addBindings() {
        InputMap inputMap = textPane.getInputMap();
        //Ctrl-b to go backward one character
        KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
        inputMap.put(key, DefaultEditorKit.backwardAction);
        //Ctrl-f to go forward one character
        key = KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK);
        inputMap.put(key, DefaultEditorKit.forwardAction);
        //Ctrl-p to go up one line
        key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
        inputMap.put(key, DefaultEditorKit.upAction);
        //Ctrl-n to go down one line
        key = KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK);
        inputMap.put(key, DefaultEditorKit.downAction);
       key = KeyStroke.getKeyStroke(KeyEvent.VK_Z,Event.CTRL_MASK);
       inputMap.put(key,undoAction);
       key = KeyStroke.getKeyStroke(KeyEvent.VK_Y,Event.CTRL_MASK);
       inputMap.put(key,redoAction);
       key = KeyStroke.getKeyStroke(KeyEvent.VK_R,Event.CTRL_MASK);
       inputMap.put(key,new StyledEditorKit.AlignmentAction("Center",StyleConstants.ALIGN_RIGHT));
       key = KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK | Event.SHIFT_MASK);
       inputMap.put(key,new StyledEditorKit.AlignmentAction("Center",StyleConstants.ALIGN_CENTER));
       key = KeyStroke.getKeyStroke(KeyEvent.VK_0,Event.CTRL_MASK);
       inputMap.put(key,new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                      printViews(textPane.getUI().getRootView(textPane),0);
       InputMap map = textPane.getInputMap();
       while(map.getParent() != null){
            map.remove(KeyStroke.getKeyStroke(KeyEvent.VK_X,KeyEvent.CTRL_MASK));
            map = map.getParent();
       map = textPane.getInputMap();
       while(map != null){
            map.remove(KeyStroke.getKeyStroke(KeyEvent.VK_V,KeyEvent.CTRL_MASK));
            map = map.getParent();
       map = textPane.getInputMap();
       while(map != null){
            map.remove(KeyStroke.getKeyStroke(KeyEvent.VK_C,KeyEvent.CTRL_MASK));
            map = map.getParent();
    //Create the edit menu.
    protected JMenu createEditMenu() {
        JMenu menu = new JMenu("Edit");
        //Undo and redo are actions of our own creation.
        undoAction = new UndoAction();
        menu.add(undoAction);
        redoAction = new RedoAction();
        menu.add(redoAction);
        menu.addSeparator();
        //These actions come from the default editor kit.
        //Get the ones we want and stick them in the menu.
        menu.add(getActionByName(DefaultEditorKit.cutAction));
        menu.add(getActionByName(DefaultEditorKit.copyAction));
        menu.add(getActionByName(DefaultEditorKit.pasteAction));
        menu.addSeparator();
        menu.add(getActionByName(DefaultEditorKit.selectAllAction));
        return menu;
    //Create the style menu.
    protected JMenu createStyleMenu() {
        JMenu menu = new JMenu("Style");
        Action action = new StyledEditorKit.BoldAction();
        action.putValue(Action.NAME, "Bold");
        menu.add(action);
        action = new StyledEditorKit.ItalicAction();
        action.putValue(Action.NAME, "Italic");
        menu.add(action);
        action = new StyledEditorKit.UnderlineAction();
        action.putValue(Action.NAME, "Underline");
        menu.add(action);
        menu.addSeparator();
        menu.add(new StyledEditorKit.FontSizeAction("12", 12));
        menu.add(new StyledEditorKit.FontSizeAction("14", 14));
        menu.add(new StyledEditorKit.FontSizeAction("18", 18));
        menu.add(new StyledEditorKit.FontSizeAction("30", 30));
        menu.addSeparator();
        menu.add(new StyledEditorKit.FontFamilyAction("Serif",
                                                      "Serif"));
        menu.add(new StyledEditorKit.FontFamilyAction("SansSerif",
                                                      "SansSerif"));
        menu.add(new StyledEditorKit.FontFamilyAction("Comical","Comic Sans MS"));
        menu.addSeparator();
        menu.add(new StyledEditorKit.ForegroundAction("Red",
                                                      Color.red));
        menu.add(new StyledEditorKit.ForegroundAction("Green",
                                                      Color.green));
        menu.add(new StyledEditorKit.ForegroundAction("Blue",
                                                      Color.blue));
        menu.add(new StyledEditorKit.ForegroundAction("Black",
                                                      Color.black));
        return menu;
    private static int tt = 0;
    protected void initDocument() {
        String initString[] =
                { "Use the mouse to place the caret.",
                  "Use the edit menu to cut, copy, paste, and select text.",
                  "Also to undo and redo changes.",
                  "Use the style menu to change the style of the text.",
                  "Use these emacs key bindings to move the caret:",
                  "ctrl-f, ctrl-b, ctrl-n, ctrl-p." };
        SimpleAttributeSet[] attrs = initAttributes(initString.length);
        try {
            for (int i = 0; i < initString.length; i ++) {
                 if(tt == 0)
                doc.insertString(doc.getLength(), initString[i] + newline,
                        attrs);
     else
          doc2.insertString(doc2.getLength(),initString[i] + newline,attrs[attrs.length-i-1]);
} catch (BadLocationException ble) {
System.err.println("Couldn't insert initial text.");
tt++;
protected SimpleAttributeSet[] initAttributes(int length) {
//Hard-code some attributes.
SimpleAttributeSet[] attrs = new SimpleAttributeSet[length];
attrs[0] = new SimpleAttributeSet();
StyleConstants.setFontFamily(attrs[0], "SansSerif");
StyleConstants.setFontSize(attrs[0], 16);
// StyleConstants.setAlignment(attrs[0],StyleConstants.ALIGN_CENTER);
attrs[1] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setBold(attrs[1], true);
// StyleConstants.setAlignment(attrs[1],StyleConstants.ALIGN_RIGHT);
attrs[2] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setItalic(attrs[2], true);
// StyleConstants.setAlignment(attrs[1],StyleConstants.ALIGN_CENTER);
StyleConstants.setStrikeThrough(attrs[2],true);
attrs[3] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setFontSize(attrs[3], 20);
attrs[4] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setFontSize(attrs[4], 12);
attrs[5] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setForeground(attrs[5], Color.red);
return attrs;
//The following two methods allow us to find an
//action provided by the editor kit by its name.
private void createActionTable(JTextComponent textComponent) {
actions = new HashMap();
Action[] actionsArray = textComponent.getActions();
for (int i = 0; i < actionsArray.length; i++) {
Action a = actionsArray[i];
actions.put(a.getValue(Action.NAME), a);
private Action getActionByName(String name) {
return (Action)(actions.get(name));
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
final TextComponentDemo frame = new TextComponentDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
frame.pack();
frame.setVisible(true);
//The standard main method.
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();

Similar Messages

  • HTML Editor Kit adding extra characters...urgent

    I am facing a strange problem in using HTML Editor Kit. I am using JTextPane to display the HTML data, which will support bold, italic and underline formatting.
    The problem is, when I
         1]Enter some text of length more than 71, with some spaces inside it ( Do not press enter key explicitly).
         2] And try to read that data from the editor kit.
    I find some new line characters inside the data as shown below in the example.
    Example :
    =========
    I entered "Testing the HTML Editor Kit functionality .. as well as Apply functionality too.. as these are giving some problems. what can be the reason. try to find out that..." in the Editor Pane and Editor Kit is generating the following HTML for it.
    <html>
    <head>
    </head>
    <body>
    <p name="Normal">
    Testing the HTML Editor Kit functionality .. as well as Apply
    functionality too.. as these are giving some problems. what can be the
    reason. try to find out that...
    </p>
    </body>
    </html>
    Although I haven't entered any new line between the paragraph tags, still you can find that the editor kit is adding some new line characters and 6 spaces from line to line. One consistency about this behavior is that it enters this stuff after 71 characters only with some special cases.
    How can we change this behavior. What all I need is I want the data in a simple string like
    "<html><head></head><body><p name="Normal">Testing the HTML Editor Kit functionality .. as well as Apply
    functionality too.. as these are giving some problems. what can be the reason. try to find out that...
    </p></body></html>"
    Any solution???
    Thanks
    Priyatam

    That's strange isn't it? Class HTMLWriter sets the line length for HTML output to 80 chars per line. Strangely JEditorPane seems not to ignore these newline chars although the actual newline is not performed within JEditorPane.
    See http://java.sun.com/j2se/1.3/docs/api/javax/swing/text/AbstractWriter.html#setLineLength(int)
    about how to set the line length.
    Hope that helps
    Cheers
    Ulrich

  • HTML Editor kit Line Space Problem

    I am using the HTMLeditor Kit i want to achieve line spacing in it. i have tried two ways one by specifying the line-height attribute directly into p tag and or secondly by using the StyleConstants attribute StyleConstants attribute StyleConstants.setLineSpacing and passing the MutableAttribute Set and linespaceno into it...
    In first case i m getting the same linespace irrespective whatever i mentioned in line-height, however if i save the backend generated html and open it in Internet Explorer it works fine.
    In second option i get content tags and but one the tag gets centre aligned and secondsly it does not woirk properly also.
    Can somebody can give me a clear insight that what i can do to achieve this line space functionality

    Yes please someone explain how to change the line spacing in a text/html accepting component, in my case JEditorPane. My need is specifically this -- I want to display variable font size text including superscripts all in HTML at a single unmoving height on JEditorPane. I believe increasing the line spacing sufficiently will enable this to happen, but how does one setLineSpacing on a JEditorPane component?
    Sorry I could'nt help the original post in this thread!

  • HTML Editor Kit

    Hi,
    I want to display following html in JEditotKit.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>ExploreCollbarativeNetworks</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <style type="text/css">
    INPUT.fancyButton
              font-family: Verdana, Arial,Georgia;
              border-right: #000000 1px solid;
              border-top: #000000 1px solid;
              font-weight: bold;
              font-size: 11px;
              border-left: #000000 1px solid;
              cursor: hand;
              color: black;
              border-bottom: #000000 1px solid;
              height: 20px;
              background-color: #F3F9FF;
    <!--
    body {
         margin-left: 0px;
         margin-top: 0px;
         margin-right: 0px;
         margin-bottom: 0px;
    .style1 {
         color: #FF7830;
         font-weight: bold;
    -->
    </style>
    <link rel="stylesheet" href="style.css" type="text/css">
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function openfile()
         document.execCommand("Open",null,"index.htm")
    function Saveasfile()
         document.execCommand("SaveAs",null,"index.htm")
    function showques()
         tot=0;
         for(i=0;i<document.form1.c.length;i++)
              if(document.form1.c.checked==true)     
                   tot=tot+1                                             
         if(tot==1)
              //alert("sssssssss")
              ob=document.getElementById('table1')
              ob1=document.getElementById('p1')
              ob.style.display="block"
              ob1.style.display="none"
              document.form1.next.disabled=true
         if(tot==2)
              ob=document.getElementById('table1')
              ob1=document.getElementById('p1')
              ob.style.display="block"
              ob1.style.display="none"
              document.form1.next.disabled=false
         //alert(tot)
    function showques1()
         ob=document.getElementById('table1')
         ob1=document.getElementById('table2')
         ob.style.display="none"
         ob1.style.display="block"
         document.form1.previous1.disabled=false
    function showques2()
         ob=document.getElementById('table1')
         ob1=document.getElementById('table2')
         ob.style.display="block"
         ob1.style.display="none"
         document.form1.previous.disabled=false
    //-->
    </SCRIPT>
    <style type="text/css">
    <!--
    .style2 {font-size: 2pt}
    .style13 {color: #000000}
    .style15 {font-size: 12px}
    .style16 {font-size: 12px; color: #000000; }
    .style17 {color: #CCCCCC}
    .style19 {color: #F1F4F8}
    .style22 {color: #FFFFFF}
    -->
    </style>
    </head>
    <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <form name="form1" method="post" action="">
    <table width="975" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
    <td>
    <TABLE border="0" cellspacing="0" cellpadding="0" width="975" align="center">
    <TR>
    <TD width="100%" >
    <TABLE width="975" border="0" align="center" cellpadding="0" cellspacing="0">
    <TR>
    <TD >
    <table width="750%" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
    <td>
    </td>
    </tr>
    <tr>
    <td>
    <table width="750" border="0" cellspacing="1" cellpadding="1" align="left" bgcolor="#FFFFFF" bordercolor="#CCCCCC">
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr>
    <td colspan="2"><img src="images/forum.gif" width="94" height="31"></td>
    </tr>
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr bgcolor="#DDEEFF" valign="middle">
    <td width="6%" height="20" align="center"><b>  <img src="images/plusbottom1.gif" width="11" height="11" align="absmiddle" id="img" border="0"></b></td>
    <td width="94%" align="left" bgcolor="#DDEEFF">
    <b> <span class="bgcolor2">Please name your
    GM partnership? </span></b></td>
    </tr>
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr>
    <td colspan="2">
    <div style="display:none" id="d1">
    <table width="734" border="0" id="t1" style="display:none" align="right">
    <tr>
    <td width="10 px" valign="top" height="20" bgcolor="#EBEBEB" >
    <div align="center"><strong>Q.1</strong></div>
    </td>
    <td width="724" bgcolor="#EBEBEB" align="left" >
    <div align="justify"><b class="bgcolor1">Please
    name your GM partnership? </b> </div>
    </td>
    </tr>
    <tr>
    <td width="10 px" valign="top" height="20" align="center" ><b>Ans</b></td>
    <td width="724" align="left" >fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf </td>
    </tr>
    <tr>
    <td width="10 px" valign="top" height="20" bgcolor="#EBEBEB" >
    <div align="center"><strong>Q.2</strong></div>
    </td>
    <td width="724" bgcolor="#EBEBEB" align="left" >
    <b>What is you role on the partnership?
    </b> </td>
    </tr>
    <tr>
    <td width="10 px" valign="top" height="20" align="center" ><b>Ans</b></td>
    <td width="724" align="left" >fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf </td>
    </tr>
    </table>
    </div>
    </td>
    </tr>
    <tr bgcolor="#DDEEFF">
    <td width="6%" bgcolor="#DDEEFF" height="20" align="center"><b >  <img src="images/plusbottom1.gif" width="11" height="11" align="absmiddle" id="img1" border="0"></b></td>
    <td width="94%" align="left"> <b> <span class="bgcolor2">Please
    name your GM partnership? </span></b></td>
    </tr>
    <tr>
    <td colspan="2"></td>
    </tr>
    <tr>
    <td colspan="2">
    <div style="display:none" id="d2">
    <table width="734" border="0" style="display:none" id="t2" align="right">
    <tr bgcolor="#EBEBEB" align="left">
    <td width="10 px" valign="top" height="20" >
    <div align="center"><strong>Q.1</strong></div>
    </td>
    <td width="724" bgcolor="#EBEBEB" align="left" >
    <div align="justify"><b>Please name your
    GM partnership? </b> </div>
    </td>
    </tr>
                                                 <tr>
    <td width="10 px" valign="top" height="20" align="center" ><b>Ans</b></td>
    <td width="724" align="left" >fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf </td>
    </tr>
    <tr bgcolor="#EBEBEB" align="left">
    <td width="10 px" valign="top" height="20" >
    <div align="center"><strong>Q.2</strong></div>
    </td>
    <td width="724" align="left" >
    <div align="justify"><b>What is you role
    on the partnership? </b>
    </div>
    </td>
    </tr>
                                                 <tr>
    <td width="10 px" valign="top" height="20" align="center" ><b>Ans</b></td>
    <td width="724" align="left" >fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf fgdhsgfjhdsgfjhsdgfhd
    dsfgdsf sdgfsdjf sdgfsdjhf sdfgsdjf dsfgdjsf
    sdhjfgdsjf dsfgdsjf sdfgsdjf sdfgsdjhf
    dsfgdjshf dsfgdsjhf dsfgdsjf </td>
    </tr>
    <tr>
    <td width="10 px"> </td>
    <td height="94%" width="724" align="left"> </td>
    </tr>
    </table>
    </div>
    </td>
    </tr>
    <tr>
    <td colspan="2"> </td>
    </tr>
    <tr>
    <td colspan="2"> </td>
    </tr>
    <tr>
    <td colspan="2"> </td>
    </tr>
    </table>
    </td>
    </tr>
    <tr>
    <td> </td>
    </tr>
    </table>
    </TD>
    </TR>
    </TABLE>
    </TD>
    </TR>
    </TABLE>
    </td>
    </tr>
    </table>
                   </form>
                   <script>
                   function show()
                        obj=document.getElementById("img")
                        obj1=document.getElementById("d1")
                        obj2=document.getElementById("t1")
                        obj3=document.getElementById("img1")
                        obj4=document.getElementById("d2")
                        obj5=document.getElementById("t2")
                        check=false
                        if(obj1.style.display=="none")
                             obj.src="images/minusbottom1.gif"
                             obj1.style.display="block"
                             obj2.style.display="block"
                             obj3.src="images/plusbottom1.gif"                         
                             obj4.style.display="none"
                             obj5.style.display="none"                         
                             check=true
                        if(!check)
                             obj.src="images/plusbottom1.gif"
                             obj1.style.display="none"
                             //alert(obj2.src)
                   function show1()
                        obj=document.getElementById("img")
                        obj1=document.getElementById("d1")
                        obj2=document.getElementById("t1")
                        obj3=document.getElementById("img1")
                        obj4=document.getElementById("d2")
                        obj5=document.getElementById("t2")
                        check=false
                        if(obj4.style.display=="none")
                             obj.src="images/plusbottom1.gif"
                             obj1.style.display="none"
                             obj2.style.display="none"
                             obj3.src="images/minusbottom1.gif"                         
                             obj4.style.display="block"
                             obj5.style.display="block"                         
                             check=true
                        if(!check)
                             obj3.src="images/plusbottom1.gif"                         
                             obj4.style.display="none"
                   </script>
                   </body>
                   </html>
    It is generated by our web designer, I am not knowing anything abt html. When i tried to display it in JEditor kit, it is not displayed properly.
    JEditorPane jPane = new javax.swing.JEditorPane();
    jPane.setDocument(getHTMLDocument());
    My getHTMLDocument() is as under :
    public HTMLDocument getHTMLDocument()
    HTMLDocument m_oHTMLMessageDoc = new HTMLDocument();
    HTMLEditorKit m_oHTMLEditor = new HTMLEditorKit();
    InputStreamReader in = null;
    m_oHTMLMessageDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
    try {
    in = new InputStreamReader(new FileInputStream("d:\\help.html"));
    m_oHTMLEditor.read(in, m_oHTMLMessageDoc, 0);
    catch (IOException ex) {
    ex.printStackTrace();
    catch (BadLocationException ex) {
    ex.printStackTrace();
    return m_oHTMLMessageDoc;
    It is displaying javascript functions as text.
    Can anybody please help me to display this html file.
    Thanks in advance,
    Dimple

    1) Swing related questions should be posted in the Swing forum.
    2) Use the "code" formatting tags when posting code, so the code is readable
    3) Swing components don't support JavaScript

  • Editor Kit Mystery behavior. I don't get how this works.

    I build a JTextPane which is editable, save it to a file, and load it back after which it's editing behavior is completely whacked out.
    The text region is originally built like this:
            textRegion = new JTextPane();
            StyledDocument doc = textRegion.getStyledDocument();
            MutableAttributeSet attr = new SimpleAttributeSet();
            StyleConstants.setForeground(attr, Color.black);
            if ( text!=null ) {
                try {
                    doc.insertString(doc.getLength(), text, attr);
                catch (BadLocationException ble) {
                    System.err.println("Couldn't insert initial text into text pane.");
            ...After which I can edit the text and change font, size, color, bold, and italic.
    Then I save the contents as a string put into a larger XML file like this:
        public String getXmlText() {
            // translate content and all its embedded style attributes into XML
            // Using class: MinimalHTMLWriter
            CharArrayWriter writer = null;
            try {
                writer = new CharArrayWriter();
                MinimalHTMLWriter htmlWriter = new MinimalHTMLWriter(writer, (StyledDocument)textRegion.getDocument());
                htmlWriter.write();
            catch (IOException ex) {
                System.out.println("Save error");
            catch (BadLocationException ex) {
                System.out.println("HTML File Corrupt");
            finally {
                if (writer != null) {
                    writer.close();
            return writer.toString();
        }Then I reload the contents from HTML String in the saved XML file like this:
        public void setXmlText( String text ) {
            // Translate HTML in "text" into styled document
            System.out.println(text);
            CharArrayReader reader = new CharArrayReader( text.toCharArray() );
            textRegion.setContentType("text/html");
            textRegion.setText(text);
        }After which the editing of the text in the JTextPane is completely messed up.
    For example, I type the text "16 point", highlight it and set it to 16 point
    font and what ends up in the saved document looks like this:
            <p>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                1
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                6
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                p
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                o
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                i
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                n
              </span>
              <span style="color: #000000; font-size: 18pt; font-family: Dialog">
                t
              </span>
            </p>Not only the wrong font size, but it puts paragraph tags between every single character I type! Why is this behaving so strangely?
    Thanks for any insights.
    --gary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Thanks,
    Well I guess there's always the solution of parsing out the HTML tags and rebuilding the document by applying styles, the way it was built in the first place.
    --gary                                                                                                                                                                                                                                                                                                                                                               

  • How to retrieve the link's label with HTML Editor kit?

    Hi all,
    I need to retrieve the label that is on a HREF html attribute.
    In other words I need to retreive the words "Home Page" from
    this snippet:
    <b>Home Page</b>
    I have found tutorials that show how to extract the link itself
    but not the label ....:-(
    can anybody help me?
    Thanks
    Francesco

    Hi,
    if you have a HTMLDocument you can look into the element structure of this document to find a certain A tag as follows   /**
       * find the next link attribute from a given element upwards
       * through the element hierarchy
       * @param elem  the element to start looking at
       * @return the link attribute found, or null, if none was found
      public static Element findLinkElementUp(Element elem) {
        Element e = null;
        Object linkAttr = null;
        Object href = null;
        while((elem != null) && (linkAttr == null)) {
          e = elem;
          linkAttr = elem.getAttributes().getAttribute(HTML.Tag.A);
          if(linkAttr != null) {
            href = ((AttributeSet) linkAttr).getAttribute(HTML.Attribute.HREF);
          elem = elem.getParentElement();
        if(linkAttr != null && href != null) {
          return e;
        else {
          return null;
      }When this method returns an element, its start and end can be used to extract the link text.
    Ulrich

  • HTML Editor

    Well, Howard Kistler has certainly already signed with an editor to sell its HTML Editor Applet. So instead of being parasites and begging for code, why not spit in our hands and code it by ourselves ?
    I've made some tries yesterday for a HTML editor application. So far, there is an appli where one can edit text, and set it bold or italic with a menu. One can also dump the HTML code to stdout.
    Here is the code, it's very simple, and after that I'll have some questions for you.
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Bla extends JFrame {
        JEditorPane jep;
        Hashtable actions;
        private Action getActionByName(String name) {
            return (Action)(actions.get(name));
        public Bla() {
            jep = new JEditorPane();
            jep.setContentType ("text/html");
            // shouldn't insert HTML test not done with a JEditorPane
            // jep.setText ("This is a <b>test</b> !!");
            // store and display available actions for this Editor Kit
            actions = new Hashtable();
            Action[] actionsArray = jep.getEditorKit().getActions();
            for (int i = 0; i < actionsArray.length; i++) {
                Action a = actionsArray;
    actions.put(a.getValue(Action.NAME), a);
    System.out.println (a.getValue(Action.NAME) + " = " + a);
    System.out.println ("TEST : " + HTMLEditorKit.BOLD_ACTION); // --> "html-bold-action" !!
    // builds menu bar
    JMenuBar jmb = new JMenuBar();
    setJMenuBar (jmb);
    JMenu jm = new JMenu("commands");
    jmb.add (jm);
    jm.add (getActionByName ("font-bold"));
    jm.add (getActionByName ("font-italic"));
    JMenuItem out = new JMenuItem("output text");
    jm.add (out);
    out.addActionListener (new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println ("CONTENT : " + jep.getText ());
    // insert editor to a scroller and add all that to our frame
    JScrollPane scroller = new JScrollPane();
         JViewport port = scroller.getViewport();
         port.add(jep);
    getContentPane().add (scroller, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pack();
    setSize (400, 400);
    show ();
    public static void main (String args[]) {
    new Bla();
    Questions :
    1) When we display HTMLEditorKit.BOLD_ACTION, the result is "html-action-bold" but this action does not exist in the action list that we got from the EditorPane ! Is it a bug or just something I didn't understand ?
    2) Is it a comprehensive list of all available actions on an EditorPane ?
    3) If you try to set the HTML text by yourself, the Editor won't like it unless it is perfectly structured (usage of <p>, by example). Strange behaviour and bugs will occur if you try it.
    4) When the HTML content is sent back, it is enclosed in <html><head></head><body>...</body></html>. What part of the architecure generates this code and how to get rid of it (not by String manipulations, of course).
    Thanks for your help. And see you soon for the next version !
    Matthieu

    I use TextWrangler and I think it rocks - it is completely free, very fast and just nice to use in general. The URL to download is:
    http://www.barebones.com/products/textwrangler/download.shtml
    Martin Bradford-Gago
    Apple Newbie Blog: http://aurora7795.blogspot.com
    MacBook, Intel Mac Mini, iMac G3   Mac OS X (10.4.8)   Using Parallels Desktop to connect to Windows XP

  • CE Trial Visual Composer Missing Kit

    Hi,
    We have installed the CE Trial 7.1 and everything worked well. But when we try to start the Visual Composer we got 271 errors in the "Layout Editor Kit" it seems that something is missing.
    Has anyone received this error too? What have you done?
    BR
    Matthias

    Hi Matthias,
    Have you installed the Adobe SVG Viewer plug-in on your browser?

  • How do I change fonts in a Text field ??

    Okay I've tried to implement a JComboBox that allows the user to change fonts in the text field. So far I've tried different methods to do it but to no avail. Could somebodoy here read the programs source code for me and tell me where I went wrong?
    /* * My GUI Client */
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import javax.swing.event.*;
    //for HTML Headers
    import javax.swing.text.StyledEditorKit.*;
    import javax.swing.text.html.HTMLEditorKit.*;
    import javax.swing.text.html.*;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkEvent.EventType;
    import javax.swing.text.html.HTMLFrameHyperlinkEvent;
    //for layout managers
    import java.awt.event.*;
    //for action and window events
    import java.io.*;
    import java.net.*;
    import java.awt.GraphicsEnvironment;
    //for font settings
    import java.lang.Integer;
    import java.util.Vector;
    import java.awt.font.*;
    import java.awt.geom.*;
    public class guiClient extends JFrame implements ActionListener {
    protected static final String textFieldString = "JTextField";
    protected static final String loadgraphicString = "LoadGraphic";
    protected static final String connectString = "Connect";
    static JEditorPane editorPane;
    static JPanel layoutPanel = new JPanel(new BorderLayout());
    static JPanel controlPanel = new JPanel(new BorderLayout());
    static JPanel buttonPanel = new JPanel(new BorderLayout());
    static JPanel fontPanel = new JPanel(new BorderLayout());
    static PrintStream out;
    static DrawPanel dPanel;
    static DrawPanel dPButton;
    static DrawPanel dFonts;
    static DrawControls dControls;
    static DrawButtons dButtons;
    static String userString;
    static String currentFont;
    String fontchoice;
    String fontlist;
    static JTextField userName = new JTextField();
    public static JMenuBar menuBar;
    private static JButton connectbutton = new JButton("Connect");
    static boolean CONNECTFLAG = false;
    //create the gui interface
    public guiClient() {
         super("My Client");
    // Create a ComboBox
    GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String envfonts[] = gEnv.getAvailableFontFamilyNames();
    Vector vector = new Vector();
    for ( int i = 1; i < envfonts.length; i++ ) {
    vector.addElement(envfonts);
    JComboBox fontlist = new JComboBox (envfonts);
         fontlist.setSelectedIndex(0);
         fontlist.setEditable(true);
         fontlist.addActionListener(this);
         fontchoice = envfonts[0];     
    //Create a regular text field.
         JTextField textField = new JTextField(10);
         textField.setActionCommand(textFieldString);
         textField.addActionListener(this);          
    //Create an editor pane.
    editorPane = new JEditorPane();
         editorPane.setContentType("text");
         editorPane.setEditable(false);
    //set up HTML editor kit
         HTMLDocument m_doc = new HTMLDocument();
         editorPane.setDocument(m_doc);
         HTMLEditorKit hkit = new HTMLEditorKit();
         editorPane.setEditorKit( hkit );
         editorPane.addHyperlinkListener( new HyperListener());
    //Create whiteboard
    dPanel = new DrawPanel();
    dPButton = new DrawPanel();
    dFonts = new DrawPanel();
    dControls = new DrawControls(dPanel);
    dButtons = new DrawButtons(dPButton);
         //JLable fontLab = new JLabel(fontLable);
    //fontLab.setText("Fonts");
    //Font newFont = getFont().deriveFont(1);
    //fontLab.setFont(newFont);
    //fontLab.setHorizontalAlignment(JLabel.CENTER);
    JPanel whiteboard = new JPanel();
    whiteboard.setLayout(new BorderLayout());
    whiteboard.setPreferredSize(new Dimension(300,300));
    whiteboard.add("Center",dPanel);
    whiteboard.add("South",dControls);
    whiteboard.add("North",dButtons);
         JScrollPane editorScrollPane = new JScrollPane(editorPane);
         editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         editorScrollPane.setPreferredSize(new Dimension(250, 145));
         editorScrollPane.setMinimumSize(new Dimension(50, 50));
    //put everything in a panel
         JPanel contentPane = new JPanel();
         JPanel fontPane = new JPanel();
         contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    //add whiteboard
         contentPane.add(whiteboard);
    //add editor box
         contentPane.add(editorScrollPane);
    //add spacer
         contentPane.add(Box.createRigidArea(new Dimension(0,5)));
    //add textfield
         contentPane.add(textField);
    //set up layout pane
         //layoutPanel.add(GridLayout(2,1),fontLab);
         layoutPanel.add( BorderLayout.NORTH, fontlist);     
         layoutPanel.add(BorderLayout.WEST,new Label("Name: ")); //add a label
         layoutPanel.add(BorderLayout.CENTER, userName ); //add textfield for user names
         layoutPanel.add(BorderLayout.SOUTH, connectbutton);//add dropdown box for fonts
         //fontPane.add(BorderLayout.NORTH,fontlist);
         contentPane.add(layoutPanel);
         contentPane.add(controlPanel);
         contentPane.add(buttonPanel);
    //Create the menu bar.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    //Build the first menu.
         JMenu menu = new JMenu("File");
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
    //a group of JMenuItems
         JMenuItem menuItem = new JMenuItem("Load Graphic", KeyEvent.VK_L);
         menu.add(menuItem);
    menuItem.setActionCommand(loadgraphicString);
         menuItem.addActionListener(this);
    connectbutton.setActionCommand(connectString);
    connectbutton.addActionListener(this);
         setContentPane(contentPane);
    static private void insertTheHTML(JEditorPane editor, String html, int location) throws IOException {
         HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
         Document doc = editor.getDocument();
         StringReader reader = new StringReader(html);
         try {
              kit.read(reader, doc, location);
         } catch (BadLocationException e) {}
    //listen for actions being performed and process them
    public void actionPerformed(ActionEvent e) {
    //if the action is from the textfield (e.g. user hits enter)
         if (e.getActionCommand().equals(textFieldString)) {
              JTextField fromUser = (JTextField)e.getSource();
         if (fromUser != null){
    //place user text in editor pane
    //send message to server
                   if (userName.getText() != null) {
                        userString = userName.getText().trim();
                   out.println(userString + ": " + fromUser.getText());
              fromUser.setText("");
         } else if(e.getActionCommand().equals(connectString)) {
              CONNECTFLAG = true;
    } else if (e.getActionCommand().equals(loadgraphicString) ) {
              final JFileChooser fc = new JFileChooser();
              int returnVal = fc.showOpenDialog(this);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fc.getSelectedFile();
                   dPanel.loadImage(file.getAbsolutePath());
                   sendImage(file);
         else if (e.getActionCommand().equals(fontlist)){
         JComboBox cb = (JComboBox)e.getSource();
    String newSelection = (String)cb.getSelectedItem();
    currentFont = newSelection;
         userString = currentFont;
    return;
    /*public void itemStateChanged (ItemEvent e) {
    if ( e.getStateChange() != ItemEvent.SELECTED ) {
    return;
    if ( list == fontlist ) {
    fontchoice = (String)fontlist.getSelectedItem();
         userString.changeFont(fontchoice);
    //append text to the editor pane and put it at the bottom
    public static void appendText(String text) {
         if (text.startsWith("ID ") ) {
              userString = text.substring(3);
         } else if (text.startsWith("DRAW ") ) {
              if (text.regionMatches(5,"LINE",0,4)) {
    dPanel.processLine(text);
         }else if (text.regionMatches(5,"POINTS",0,5)) {
         dPanel.processPoint(text);
         } else if (text.startsWith("IMAGE ") ) {
    int len = (new Integer( text.substring(6, text.indexOf(",")))).intValue();
    //get x and y coordinates
         byte[] data = new byte[ (int)len ];
         int read = 0;
    try {
         while (read < len) {
         data = text.getBytes( text.substring(0, len) );
    } catch (Exception e) {}
         Image theImage = null;
         theImage = dPanel.getToolkit().createImage(data);
         dPanel.getToolkit().prepareImage(theImage, -1, -1, dPanel);
         while ((dPanel.getToolkit().checkImage(theImage, -1, -1, dPanel) & dPanel.ALLBITS) == 0) {}
              dPanel.drawPicture(0, 0, theImage);
    } else {
    //set current position in editorPane to the end
              editorPane.setCaretPosition(editorPane.getDocument().getLength());
    //put text into the editorPane
              try {
                   insertTheHTML(editorPane, text, editorPane.getDocument().getLength());
              } catch (IOException e) {}
    } //end of appendText(String)
    public void sendImage(File file) {
    //find length of file
         long len = file.length();
    //read file into byte array
         byte[] byteArray = new byte[(int)len];
         try {
              FileInputStream fstream = new FileInputStream(file);
              if (fstream.read(byteArray) < len) {
    //error could not load file
              } else {
              out.println("IMAGE " + len + ",");
                   out.write(byteArray, 0, (int)len); //write file to stream
         } catch(Exception e){}
    //run the client
    public static void main(String[] args) {
         String ipAddr=null, portNr=null;
              if (args.length != 2) {
                   System.out.println("USAGE: java guiClient IP_Address port_number");
                   System.exit(0);
              } else {
         ipAddr = args[0];
              portNr = args[1];
              JFrame frame = new guiClient();
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) { System.exit(0); }
              frame.pack();
              frame.setVisible(true);
              while(CONNECTFLAG == false){}
    //sames as previous client,
    //set up connection and then listen for messages from the Server
              String socketIP = ipAddr;
              int port = Integer.parseInt(portNr);
    //the IP address of the machine where the server is running
              Socket theSocket = null;
    //communication line to the server
              out = null;
    //for message sending
              BufferedReader in = null;
    //for message receiving
              try {
              theSocket = new Socket(socketIP, port );
    //try to connect
              out = new PrintStream(theSocket.getOutputStream());
                   dPanel.out = out;
    //for client to send messages
              in = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
                   BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
                   String fromServer;
                   while ((fromServer = in.readLine()) != null) {
                   appendText(fromServer);
                   if (fromServer.equals("BYE")) {
                        appendText("Connection Closed");
                        break;
              out.close();
    //close all streams
              in.close();
              theSocket.close();
    //close the socket
         } catch (UnknownHostException e) {
    //if the socket cannot be openned
              System.err.println("Cannot find " + socketIP);
              System.exit(1);
              } catch (IOException e) { //if the socket cannot be read or written
              System.err.println("Could not make I/O connection with " + socketIP);
              System.exit(1);
    class HyperListener implements HyperlinkListener {
    public JEditorPane sourcePane;
    public void hyperlinkUpdate(HyperlinkEvent e) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
    sourcePane = (JEditorPane) e.getSource();
                   if (e instanceof HTMLFrameHyperlinkEvent) {
    HTMLFrameHyperlinkEvent event = (HTMLFrameHyperlinkEvent) e;
                        System.out.println(event.getTarget());
                        HTMLDocument doc = (HTMLDocument) sourcePane.getDocument();
                        doc.processHTMLFrameHyperlinkEvent(event);
    else {
    try {}
    catch (Exception ev){
         ev.printStackTrace();
    Well sorry the source code takes up the whole forum but I need a good feedback from this.

    All right...
    public class guiClient extends JFrame implements ActionListener {
    static String userString;
    static String currentFont;
    String fontchoice;
    String fontlist;
    static JTextField userName = new JTextField();
    public guiClient() {
         super("My Client");
    public guiClient() {
         super("My Client");
    // Create a ComboBox
    GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String envfonts[] = gEnv.getAvailableFontFamilyNames();
    Vector vector = new Vector();
    for ( int i = 1; i < envfonts.length; i++ ) {
    vector.addElement(envfonts);
    JComboBox fontlist = new JComboBox (envfonts);
         fontlist.setSelectedIndex(0);
         fontlist.setEditable(true);
         fontlist.addActionListener(this);
         fontchoice = envfonts[0];     
    //Create a regular text field.
         JTextField textField = new JTextField(10);
         textField.setActionCommand(textFieldString);
         textField.addActionListener(this);
    public void actionPerformed(ActionEvent e) {
    //if the action is from the textfield (e.g. user hits enter)
         if (e.getActionCommand().equals(textFieldString)) {
              JTextField fromUser = (JTextField)e.getSource();
         if (fromUser != null){
    //place user text in editor pane
    //send message to server
                   if (userName.getText() != null) {
                        userString = userName.getText().trim();
                   out.println(userString + ": " + fromUser.getText());
              fromUser.setText("");
         else if (e.getActionCommand().equals(fontlist)){
         JComboBox cb = (JComboBox)e.getSource();
    String newSelection = (String)cb.getSelectedItem();
    currentFont = newSelection;
         userString = currentFont;
    return;

  • Adding text to a RTF document

    I'm reposting this because my last post was very poorly written. I have a JTextPane that uses a RTF editor kit, and what I want to do is add some text to the very beginning and end of the document with out losing the formatting of the RTF. What I do now is get a string from the Editor Kit that is RTF text but I can't just add to the front because of the formatting there, {rtf and all that jazz. What I do is use the getText() function to get just the unformatted text, then get the first 10 chars, and then search for that in the RTF string, and insert text there. It seems to be a bit of a crude way to go about it; even so I would be fine with it if it didn't fail with non-English characters. (You know like the French e with the accent or the German u with the 2 dots). So what I�m looking for is some sort of way to insert the text programmatically eliminating the need for searching and all that. Any help will be greatly appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Forgive me if you know this already but I'd like to offer what I can...
    The JTextComponent (and it's subclasses) makes use of a Document for a lot of its Model. If you haven't set a different one explicitly, then the RTFEditorKit will see that an appropriate StyledDocument is used on your JTextPane. The Document interface allows for raw text (without markup, formatting, etc) to be mutated with optional formatting attributes (inserts, replaces, etc.).
    I think what you are looking for lies in the Document of the JTextPane. The getDocument() method will return the Document holding the text and can be mutated at will (either by typing into the component or programmatically inserting text).
    When you call getText() on your text component, the call is delegated to the installed editor kit and returns the contents. The text component calls the write( Writer, .... ) on the EditorKit but the RTFEditorKit actually should throw an exception and cause null to be returned from the getText() method of JEditorPane. To get the marked up, rtf text you would need to call the write( OutputStream, ... ) method.
    Here is programmatic insertion at the beginning and end...
        JTextPane textPane = new JTextPane();
        textPane.setEditorKit( new RTFEditorKit() );
        //pretend we've grabbed an rtf file and set it's contents with the setText() method.
        Document doc = textPane.getDocument();
        try{      
            doc.insertString( 0, "begin", null );
            doc.insertString( doc.getLength(), "end", null );
        }catch( BadLocationException ex ){
            //what ever you need to do
        //now of course to get the rtf formatted string out of the editor kit
        //you need to write it to an OutputStream (i.e. System.out, a FileOutputStream, etc.)
        try{
            textPane.getEditorKit().write( System.out, doc, 0, doc.getLength() );
        }catch( BadLocationException ex ){
            //what ever you need to do
        }catch( IOException ex ){
            //what ever you need to do
        }I didn't pass any formatting attributes into the calls of the insertString method but you could easily do that if you need to.
    Hope that helps!
    Matt

  • Using the swing clipboard and DefaultEditorKit.copytAction

    Hi all
    Ive heard that i can use the swing DefaultEditorKit to basically copy and paste text throughout my application (like using Ctrl+C ctrl+V)
    basically i have a number of elements such as textpanes and edit boxes and i want to be able to copy and paste text between them with the least amount of effort, most examples i have seen about implementing copy and paste require you to specify the elements that you need to copy and paste from
    i dont want to have to specify every element, i just want a simple action that says copy the selected text, and paste the selected text (dont have to worry about cut really)
    Ctrl+C and Ctrl+V both do this natrually, but how do i call a simple method that does the same thing that the keystrokes do.
    I just want two menu items that when i invoke their click listeenrs to say something like
    copylistener{
    copy();
    Ive seen a few examples of the swing methods but these also seem to need to invoke actions on the elements that you want to copy and paste between, but the keystroke dont need any of this

    Sorry, I see your confusion now.
    Yes, you need a few helper methods to get the actual Action, but you don't need to do this for every text component because the Action is shared by all text components.
    Text components use an EditorKit. The editor kit provides support for basic functionality of each text component. (ie. cursor movement, text selection, cut, copy, paste...). The EditorKit uses Actions to implement the basic support. Each Action extends TextAction which contains a method "getFocusedComponent" which returns the last text component that currently has focus. (clicking on a menu item is only a temporary loss of focus).
    So the code in the TextComponentDemo is being very efficient and is reusing the static Action that was created by the DefaultEditorKit. So even though your form may have multiple text components, you only need to create your menu item once using any text component.
    If you don't want your code to reuse the existing Actions, you can create your own Action directly from the EditorKit. Then this Action can be used to create a JMenuItem or JButton. Here is a simple example of using this approach:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302962

  • Editable and Non editable portion in JTextArea

    hi all
    i have following problem:
    in my application i m using JTextArea and JButton when button is clicked some text is added as follows with append method
    textarea.append("darshan");
    textarea.append("\n\n");
    textarea.append("gajjar");
    now i want the text in textarea noneditable (ie 'darshan','gajjar') while other portion is editable (ie '\n\n')
    it means i can enter or change text between two texts 'darshan' and 'gajjar' but i can not edit 'darshan' and 'gajjar'.
    and finally i want to save thest text in a file
    please help me
    thanks
    darshan

    Hi,
    You have to use JEditorPane and linkit with extended HTMLDocument.
    this methods override HTMLDocument methods and make the content between
    to tags (in this example between tag<template>) not editable. There are some bugs to fix here but i hope that this will help.
    kit object is HTMLEditorKit instance of current JEditorPane editor kit.
    public void insertString(int offs, String str, AttributeSet a) throws
          BadLocationException {
        if (kit == null) {
          super.insertString(offs, str, a);
          return;
        if (!canEditTemplate) {
          Element curTag = kit.getCharacterAttributeRun();
          Element parent = curTag.getParentElement();
          try {
            int i = 0;
            for (; i < parent.getElementCount(); i++) {
              if (parent.getElement(i).equals(curTag)) {
                break;
            if (i != 0) {
              Element prev = parent.getElement(i - 1);
              Element next = parent.getElement(i + 1);
              if (prev.getName().equalsIgnoreCase("template") &&
                  next.getName().equalsIgnoreCase("template")) {
                System.out.println("Tempate element not editable");
                return;
          catch (ArrayIndexOutOfBoundsException exxx) {}
          catch (NullPointerException exe) {
            System.out.println("nullPointer in template insert");
        super.insertString(offs, str, a);
      public void remove(int offs,
                         int len) throws BadLocationException {
        if (!canEditTemplate) {
          if (kit == null) {
            super.remove(offs, len);
            return;
          Element curTag = kit.getCharacterAttributeRun();
          Element parent = curTag.getParentElement();
          try {
            int i = 0;
            for (; i < parent.getElementCount(); i++) {
              if (parent.getElement(i).equals(curTag)) {
                break;
            if (i != 0) {
              Element prev = parent.getElement(i - 1);
              Element next = parent.getElement(i + 1);
              if (prev.getName().equalsIgnoreCase("template") &&
                  next.getName().equalsIgnoreCase("template")) {
                System.out.println("Tempate element not editable");
                return;
          catch (ArrayIndexOutOfBoundsException exxx) {}
          catch (NullPointerException exe) {
            System.out.println("nullPointer in template remove");
            return;
        super.remove(offs, len);

  • Help to show a HTML file in Swing

    Hiiiiiiiiiii,
    During my development Me in a problem . Please help me out.
    As per my current context of the project I have to develop a HTML page with Help of CSS and all other things. After that I have to Show the HTML file through Swing. I know how to attach a file with help of URL but need some help to show a HTML file in Swing.
    *help to show a HTML file in Swing*

    As camickr said Javascript support is not available. If you want to support you have to write code for that. Up to an extent CSS support is provided.
    Sample code to display HTML pages in JTexPane (you can use JEditorPane as well):
    Construct the URL:
    URL url = YourClass.class.getResource("resources/Hello.html");
    // If YourClass is in package test.html, then your html page must be available in .....test/html/resources directory.
    // And your CSS files must be accessible from your HTML page. This you can test by simply opening the html
    // page in your favorite browser.And then call setPage() method of HelpDataPane. Note that, HelpDataPane supports hyperlink activation.
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.JTextPane;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
    * A pane to display help pages. Help pages are accessed as URL and displayed
    * in this pane.
    * @author Mrityunjoy Saha
    * @version 1.0
    public class HelpDataPane extends JTextPane {
         * Creates a new instance of {@code HelpDataPane}.
        public HelpDataPane() {
            super();
            this.addHyperlinkListener(new HyperlinkListener() {
                public void hyperlinkUpdate(HyperlinkEvent e) {
                    if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                        setPage(e.getURL());
         * Sets the current URL being displayed.  The content type of the
         * pane is set, and if the editor kit for the pane is
         * non-{@code null}, then
         * a new default document is created and the URL is read into it.
         * @param page The URL to be displayed.
        @Override
        public void setPage(URL page) {
            try {
                super.setPage(page);
            } catch (IOException ex) {
                try {
                    URL blankURL = YourClass.class.getResource("resources/Blank.html");
                    super.setPage(blankURL);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
    }Thanks,
    Mrityunjoy

  • Swing Text Documents Help

    We have a large application that includes an editor for users to create and edit various documents.
    We are using a JEditorPane that displays custom documents tailored to our requirements (via a custom editor kit, etc). These vary from simple 'Word' style user interfaces to more elaborate graphical data entry forms.
    The problem we are facing is that no matter what content the JEditorPane is displaying there is always a line at the bottom of the pane that the text caret can get to that is not part of our documents and does not allow the user to type into this space. This being there isn't causing any major problems just very annoying that we can't figure out how to get rid of it.
    A temporary solution for the moment has been to add a caret listener to the editor and if the caret position goes to the last position in the document it moves it back a space (messy, but it works for the moment).
    Has anyone else experienced something similar to this?#
    Any help appreciated.

    DefaultStyledDocument seems to be the problem.
    Our class extends this.
    It contains a paragraph with "/n" when it is created and this doesn't seem to get removed when we add our content (via create(es)) and we can't remove it manually afterwards.
    The elaborate slightly
    calling dump() before we create out document gives something along the lines of (I've removed a few carrage returns and replaced them with \n to make it easier to look at): -
    <section>
    <paragraph resolver=NamedStyle:default {name=default,nrefs=1}>
    <content>
    [0,1][\n]
    <bidi root>
    <bidi level bidiLevel=0>
    [0,1][\n]
    We then call create(es) where es is an array of ElementSpecs
    The array consists of element specs with the following attributes (or a rough description of them).
    0 StartTagType (Start)
    1 StartTagType (Start of our report)
    2 StartTagType (Start of a paragraph with font attributes, etc)
    3 ContentType (Our content where length=5 data = "blah\n")
    4 EndTagType (End of paragraph with font attributes)
    5 StartTagType (Start of a new paragraph)
    6 ContentType (More content where length=1 data="\n")
    7 EndTagType (End of paragraph with font attributes)
    8 EndTagType (End of our report)
    9 EndTagType (End)
    The first thing the create method in DefaultStyledDocument does is
    if (getLength() != 0) {
    remove(0, getLength());
    getLength returns 0 even though "/n" is there (as you described above). Hence remove(o, getLength()) never gets called. If I try and get clever and call the remove method after the create method using something like remove(getLength()-1, getLenght()) or even: -
    Element element = this.getParagraphElement(getLength());
    int startOffset = element.getStartOffset();
    int endOffset = element.getEndOffset();
    this.remove(startOffset, endOffset-startOffset);
    it never has any effect.
    If I call dump() again after the create method I get something along the lines of : -
    <section>
    <REPORT
    foreground=java.awt.Color[r=128,g=128,b=128]
    $ename=REPORT
    CHANGED=hss.radiology.reports.ReportDocument$ChangedMarker@39471b
    READONLY=true
    REPORT=hss.cris3.Report@37cee4
    >
    <paragraph
    $ename=paragraph
    family=Verdana
    size=18
    >
    <content>
    [0,5][blah\n]
    <paragraph
    $ename=paragraph
    family=Verdana
    size=18
    >
    <content>
    [5,6][\n]
    <paragraph resolver=NamedStyle:default {name=default,nrefs=1}
    >
    <content>
    [6,7][\n]
    <bidi root>
    <bidi level
    bidiLevel=0
    >
    [0,7][blah\n\n\n]
    Does anyone have any ideas of how i may be able to remove the last paragraph?
    Thanks, Paul

  • Interfacing StyledDocument and XML

    Hello,
    I'm trying to make an xml editor, but am stumped on the javax.swing.text.StyledDocument interface. The problem is that DefaultStyledDocument isn't suited to store xml, and HTMLStyledDocument is well, html. What I want is a document class that can easily interface with the myriad of xml technologies out there (e.g. the org.w3c.dom classes)... so I think I need to create my own, as well as an editor kit. [shudder  :-o ]
    Has anyone attempted this / seen tutorials / have tips ?
    Thanks in advance

    The Document model only stores one character ("\n") for each new line entered.
    When you do a statement like:
    String str = textPane.getText();
    The newline characters in the document are replaced with the newline string for the target operating system:
    a) for Unix - "\n"
    b) for Windows - "\r\n").
    Therefore, the length of the String in Windows will always be greater by the number of lines in your Document.
    The way I have gotten around this problem is to change the End-Of-Line string that is added when using the getText() by using the following code:
    textPane.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
    Note: if you ever intend to write the contents of the text pane to a file then your code should be something like:
    a) String eol = textPane.getDocument().getProperty( DefaultEditorKit.EndOfLineStringProperty );
    b) textPane.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
    then before writing to the file you would do:
    c) textPane.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, eol );

Maybe you are looking for

  • BEx Error: Automation error: Object invoked has disconnected from clients

    Hi, We have a user here that attempts to access a query in BEx (MS Excel), but receives this error message: - Runtime error '-2147417848 (80010108)':   Automation error   The object invoked has disconnected from its clients. Any ideas. Thanks, John

  • Table for errors on sales order

    Sincere. I would like to know, where in CRM can I get table of errors, that can be shown at sales order. I already know about table T100, which includes all the texts for specific errors, but where can I get this errors. I would like to generate a re

  • How to display the data?

    hi all, Im using Java NetBeans IDE 4.1 to create an application. I have connected my apllication to MS Access database by ODBC and then retrieved the data of a field named "student-name" by using method b]ResultSet() , this retrieve all of the name s

  • Exeuting a file in another forest

    Hello Community     Using Windows 2008 Server on a network there is a file that I am attemping to execute in another forest.     Lets call them Forest1/Domain1(trusted) and Forest2/Domain2(trusting) in a One-Way Trust Relationship.     Server1 is in

  • View Adobe Illustrator files on iPhone

    I've looked everywhere and can't believe I'm the only creative professional who wouldn't enjoy being able to open e-mail attachments that were Adobe Illustrator or EPS files the same way you can view a pdf. There is no app that i've found that does t