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

Similar Messages

  • Replace string in text document help please

    I am trying to make a simple program that changes all "http://" to "https://ssl." in a text document. This is the code I have created so far but the program is not working as intended. I am making this program so I can quicky change the links on my website to the secure webpages.
    import java.io.*;
    public class Main {
        public static void main(String[] args) {
            try {
                File f = new File("textFile.txt");
                RandomAccessFile raf = new RandomAccessFile(f , "rw");
                String line = raf.readLine();
                while(line != null){
                line = line.replaceAll("http://" , "https://ssl.");
                raf.writeChars(line);
                line = raf.readLine();
                raf.close();
            } catch (IOException e) {
    }Any help welcome!

    This is not a Java thing, but a general fact about files and I/O:
    You can't edit a file in place. Do this:
    1. Read the original file a line at a time.
    2. Edit each line and write them out to a new file.
    3. When you are done, close the files. Delete the original file and then rename the new file to the old file's name.

  • Immutable String in a swing.text.Document

    Hello,
    I want to add to a text component an 'immutable' bit of text. That is a string that is one 'item', it can not be broken or split. If for example if you wanted to delete you would have to delete the whole thing, not part of it.
    Does anyone know how to do this?
    I'm currently using a JTextPane and struggling with the Document interface.
    Some context to this. I'm building a widget like the Outlook 'to field'. You type text in and it looks up that text in a list of contacts. You can select from the list. When you do this the contact is added to the text box and is underlined and made bold and becomes 'immutable' in the way that I have explained above.
    In an ideal World I would want to do this :
    be able to add a ContactElement to the text pane. Be able to specifiy that ContactElements are to be rendered in bold and underlined and would display the name attribute of the Contact object. These ContactElements would be 'immutable' as described above. Get a list of the ContactElements in the text pane and thus the contacts displayed.
    hope that makes sense, all help gratefully received,
    thanks, Tom

    When you insert a ContactElement, create two Position objects representing the start and end points of the element, and save them. Whenever the user moves the caret, refer to your list of ContactElement end points to see whether the new location is inside one. If it is, either whisk the caret to the other end or select the whole thing, whatever seems appropriate. I've never used it, but I believe NavigationFilter is the tool for that job.
    Any time text is deleted, you'll need to check the list to see if the deleted section contained any ContactElements, and to remove them from the list if so. I was going to recommend using a DocumentListener for that, but I don't think it would work; all the Positions would already have been updated. I suggest using a DocumentFilter to update the list before deleting the text.
    One complication that occurs to me is searching, or other operations that involve programmatic selection or highlighting. The NavigationFilter is too low-level; you'll have to make sure the search feature doesn't look inside ContactElements. You'll probably find other higher-level tasks that need to be aware of ContactElements so they can treat them specially.

  • Merge 2 javax.swing.text.Documents

    Can I somehowmerge 2 styled documents?
    I have 2 JEditPanes with 2 styled docs and I want to append first one at the end of second one.

    (When I say styled, I mean, that I have already set some attibutes and I want them in the other document, I know, how to append plain text with insertString)

  • Arabic numerals not displaying in Swing text components

    On a test system setup with Windows NT Arabic version, we had problems entering Arabic numerics into Swing text components.
    Other Arabic characters were displayed correctly, but numerals were all represented by Western characters ('0 to 9'). Even when using the "Alt-" method to enter the Unicode character codes via. the keypad, we still got incorrect characters.
    When using the keypad to enter the code '\u0660' (Arabic "1"), the code sent to the text component was '\u2022' (Bullet).
    We tried this on an English system and the same code was passed to the text component.
    Does anyone have any suggestions as to what might be the cause of this problem ?
    Thanks,
    Brian...

    hello!
    I am developing an arabic editor but i am unable to display the arbic numeric in swing text .Plz help me on this topic and send some code example on this topic.
    I have another problem about events i.e how can i handle the beckspace event, enter event, and spaceevent?
    plz send me mail .
    Thanx for advance.

  • AAARGH!!! Can't understand javax.swing.text.*

    Good afternoon...
    does anybody understand javax.swing.text classes? i've read a number of
    books, downloaded docs (including those from the javax.swing.text author), and googled everything i could think of. but nothing seems to explain it to me so that i can understand it! maybe i'm just dense, but maybe it really is that difficult.
    i want to create a read-only document, who's source is not necessarily a
    string, but perhaps an ArrayList of objects with a HashMap of attributes. or even something simpler for now, just an object with a fixed number of attributes. i want to display this information in a JTextArea. i tried implementing a Document and passing it to the JTextArea constructor but just got a NullPointerException.
    does anybody know where i can find more information on creating my own
    document types?
    here's the code for my ReadOnlyDocument class if anyone of you are generous (& adventurous) enough to take a look:
    import java.util.ArrayList;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.UndoableEditListener;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.Position;
    import javax.swing.text.Segment;
    public class ReadOnlyDocument implements Document{
        private String myContent = "this is the contents of my document!";
        private ArrayList listeners;
        private ReadOnlyDocument refSelf = this;
        public ReadOnlyDocument() {
         System.out.println("ReadOnlyDocument.<init>");
        public int getLength() {
         System.out.println("ReadOnlyDocument.getLength() = " + myContent.length());
            return myContent.length();
        public void addDocumentListener(DocumentListener listener) {
         System.out.println("ReadOnlyDocument.addDocumentListener(" + listener + ")");
            if (listeners != null) {
                listeners = new ArrayList();
                listeners.add(listener);
            } else {
                listeners = new ArrayList();
                listeners.add(listener);
        public void removeDocumentListener(DocumentListener listener) {
         System.out.println("ReadOnlyDocument.removeDocumentListener(" +
    listener + ")");
            if (listeners != null) {
                listeners.remove(listener);
        public void addUndoableEditListener(UndoableEditListener listener) {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.addUndoableEditListener(" +
    listener + ")");
        public void removeUndoableEditListener(UndoableEditListener listener) {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.removeUndoableEditListener(" +
    listener + ")");
        public Object getProperty(Object key) {
            System.out.println("ReadOnlyDocument.getProperty(" + key + ") =
    null");
            return null;
        public void putProperty(Object key, Object value) {
               System.out.println("ReadOnlyDocument.putProperty(" + key + ")");
        public void remove(int offs, int len) throws BadLocationException {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.remove(" + offs + ", " + len +
        public void insertString(int offset, String str, AttributeSet a) throws
    BadLocationException {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.insertString(" + offset + ", " +
    str + ", " + a + ")");
        public String getText(int offset, int length) throws
    BadLocationException {
         System.out.print("ReadOnlyDocument.getText(" + offset + ", " + length +
    ") = ");
            if ((offset >= 0) && (length >= 0) && (offset+length <=
    myContent.length()+1)) {
             System.out.println(myContent.substring(offset, offset+length-1));
                return myContent.substring(offset, offset+length-1);
            } else {
             System.out.println("BadLocationException!");
                throw new BadLocationException("Bad location requested", 0);
        public void getText(int offset, int length, Segment txt) throws
    BadLocationException {
         System.out.print("ReadOnlyDocument.getText(" + offset + ", " + length +
    ", " + txt + ") = ");
            if ((offset >= 0) && (length >= 0) && (offset+length <=
    myContent.length()+1)) {
             System.out.println(myContent.substring(offset, offset+length-1));
                txt = new Segment(myContent.toCharArray(), offset, length);
            } else {
             System.out.println("BadLocationException!");
                throw new BadLocationException("Bad location requested", 0);
        public Position getStartPosition() {
         System.out.println("ReadOnlyDocument.getStartPosition() = 0");
      return new Position() {
       public int getOffset() {
        return 0;
        public Position getEndPosition() {
         System.out.println("ReadOnlyDocument.getEndPosition() = " +
    myContent.length());
      return new Position() {
       public int getOffset() {
        return myContent.length();
        public Position createPosition(int offs) throws BadLocationException {
         System.out.println("ReadOnlyDocument.createPosition(" + offs + ") =
    0");
            if ((offs >= 0) && (offs <= myContent.length()-1)) {
       return new Position() {
        public int getOffset() {
         return 0;
      } else {
       throw new BadLocationException("Bad location requested", 0);
        public Element[] getRootElements() {
         System.out.println("ReadOnlyDocument.getRootElements()");
         Element[] roots = {new Element() {
       public Document getDocument() {
        return refSelf;
       public Element getParentElement() {
        return null;
       public String getName() {
        return "ReadOnlyRoot";
       public AttributeSet getAttributes() {
        return null;
       public int getStartOffset() {
        return 0;
       public int getEndOffset() {
        return myContent.length() - 1;
       public int getElementIndex(int offset) {
        return 0;
       public int getElementCount() {
        return 0;
       public Element getElement(int index) {
        return null;
       public boolean isLeaf() {
        return true;
      return roots;
        public Element getDefaultRootElement() {
         System.out.println("ReadOnlyDocument.getDefaultRootElement()");
      return new Element() {
       public Document getDocument() {
        return refSelf;
       public Element getParentElement() {
        return null;
       public String getName() {
        return "ReadOnlyRoot";
       public AttributeSet getAttributes() {
        return null;
       public int getStartOffset() {
        return 0;
       public int getEndOffset() {
        return myContent.length() - 1;
       public int getElementIndex(int offset) {
        return 0;
       public int getElementCount() {
        return 0;
       public Element getElement(int index) {
        return null;
       public boolean isLeaf() {
        return true;
        public void render(Runnable r) {
            // not sure what to put here
         System.out.println("ReadOnlyDocument.render(" + r + ")");
    }and here's a simple class to display the document/generate the error:
    import java.awt.event.*;
    import javax.swing.*;
    public class ReadOnlyFrame extends JFrame {
    public ReadOnlyFrame() {
      super();
      setTitle("Read Only Document");
      addWindowListener(new WindowAdapter() {
       public void windowClosed(WindowEvent e) {
        System.exit(0);
      getContentPane().add(new JTextArea(new ReadOnlyDocument()));
      setSize(200, 200);
    public static void main(String[] args) {
      ReadOnlyFrame rof = new ReadOnlyFrame();
      rof.setVisible(true);
    Headed for the second star to the right and straight on till morning...
    Eric Schultz
    aka: Storkman
    http://community.webshots.com/user/storky1
    mailto:EricSchultzATcanadaDOTcom

    if you are getting that print before the timer
    starts, then I'd expect it's not blocking. The
    problem with these small snippets of code is that we
    can't really tell what might be going on elsewhere.Yes, I realize that. AAMOF, there isn't anything going on elsewhere, i.e.
    the GestureController object spawns another thread when it gets
    created. That other thread blocks until a 'Mover' object is delivered to
    the GestureController object. The mutex/synchronizing stuff works
    like the textbook version, i.e. no deadlock, no deadly embrace, no
    nothing. When the timer is started, the Mover is supposed to
    call back the 'animate' method, just a method in the GestureController
    object.
    All the System.out.prints show that it gets there. The task (an ActionListener)
    dispatched by that timer doesn't start. As you can see above, I've
    used System.out.prints for that too. It is as if that Timer doesn't start.
    I still haven't found anything ... This is what the 'auto.move' thing is
    supposed to do:     static class DragMover implements Mover {
              DrawableStack from;
              DrawableStack to;
              int position;
              DragMover(DrawableStack from, int position, DrawableStack to) {
                   this.from= from;
                   this.to  = to;
                   this.position= position;
              public void move() {
                   System.out.println("moving the stuff...");
                   GestureController.getGestureController().animate(from, position, to);
              public void undo() { }          
         }... the line "moving stuff ..." isn't displayed either, i.e. the actionPerformed
    method is never called and then ... there's nothing in between there, i.e.
    the Timer is supposed to call that method.
    Thank you for your reply, much appreciated and,
    kind regards,
    Jos
    by that timer (an ActionListener)

  • Many javax.swing.text.Position objects en masse

    Hi,
    I am wondering if anyone has much experience with the performance of javax.swing.text.Document implementations (using GapContent) and a large number of registered Position objects. I am trying to keep track of token boundaries for quick re-lexing, and the token count can be rocket high. I am just beginning to work with this API, and I guess I am looking for any insider information I may be missing.
    Thanks,
    galaxy

    Hi,
    I am wondering if anyone has much experience with the performance of javax.swing.text.Document implementations (using GapContent) and a large number of registered Position objects. I am trying to keep track of token boundaries for quick re-lexing, and the token count can be rocket high. I am just beginning to work with this API, and I guess I am looking for any insider information I may be missing.
    Thanks,
    galaxy

  • Using Pages 5.2.2: When I drag an image into my document, I lose the related text.  I can crop the image, make it smaller, but it is surrounded by blankness that overrides the text.  Help?!

    Using Pages 5.2.2, MacBook Pro, OSX 10.9.5:  I cannot drag an image into my document without it obliterating the text.  Even after re-sizing,  the image just becomes small inside a larger blank area that appears to cover the saved text.  Help?

    Using Pages 5.2.2, MacBook Pro, OSX 10.9.5:  I cannot drag an image into my document without it obliterating the text.  Even after re-sizing,  the image just becomes small inside a larger blank area that appears to cover the saved text.  Help?

  • [HELP! ] why my program thows a javax.swing.text.ChangedCharSetException?

    there's the source:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.border.*;
    class HTMLMagician extends JFrame
         protected static final String APP_NAME="HTML Magician V1.0 Produced By V Studio";
         protected JTextPane hm_textPane;
         protected StyleSheet hm_styleSheet;
         protected HTMLEditorKit html_kit;
         protected HTMLDocument html_document;
         protected JMenuBar hm_menuBar;
         protected JToolBar hm_toolBar;
         protected JFileChooser hm_fileChooser;
         protected File current_file;
         protected boolean text_changed=false;
         public HTMLMagician()
              super(APP_NAME);
              setSize(800,600);
              getContentPane().setLayout(new BorderLayout());
              produceMenuBar();
              hm_textPane=new JTextPane();
              html_kit=new HTMLEditorKit();
              hm_textPane.setEditorKit(html_kit);
              JScrollPane textPane_scrollPane=new JScrollPane();
              textPane_scrollPane.getViewport().add(hm_textPane);
              getContentPane().add(textPane_scrollPane,BorderLayout.CENTER);
              hm_fileChooser=new JFileChooser();
              javax.swing.filechooser.FileFilter hm_filter=new javax.swing.filechooser.FileFilter()
                   public boolean accept(File pathname)
                        if(pathname.isDirectory())
                             return true;
                        String ext_name=pathname.getName().toLowerCase();
                        if(ext_name.endsWith(".htm"))
                             return true;
                        if(ext_name.endsWith(".html"))
                             return true;
                        if(ext_name.endsWith(".asp"))
                             return true;
                        if(ext_name.endsWith(".jsp"))
                             return true;
                        if(ext_name.endsWith(".css"))
                             return true;
                        if(ext_name.endsWith(".php"))
                             return true;
                        if(ext_name.endsWith(".aspx"))
                             return true;
                        if(ext_name.endsWith(".xml"))
                             return true;
                        if(ext_name.endsWith(".txt"))
                             return true;
                        return false;
                   public String getDescription()
                        return "HTML files(*.htm,*.html,*.asp,*.jsp,*.css,*.php,*.aspx,*.xml)";
              hm_fileChooser.setAcceptAllFileFilterUsed(false);
              hm_fileChooser.setFileFilter(hm_filter);
              try
                   File dir=(new File(".")).getCanonicalFile();
                   hm_fileChooser.setCurrentDirectory(dir);
              }catch(IOException ex)
                   showError(ex,"Error openning current directory");
              newDocument();
              WindowListener action_winClose=new WindowAdapter()
                   public void windowClosing(WindowEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(action_winClose);
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setVisible(true);
         protected void produceMenuBar()
              hm_menuBar=new JMenuBar();
              hm_toolBar=new JToolBar();
              JMenu menu_file=new JMenu("File");
              menu_file.setMnemonic('f');
              ImageIcon icon_new=new ImageIcon("imgs/file.gif");
              Action action_new=new AbstractAction("New",icon_new)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        newDocument();
              JMenuItem item_new=new JMenuItem(action_new);
              item_new.setMnemonic('n');
              item_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
              menu_file.add(item_new);
              JButton button_new=hm_toolBar.add(action_new);
              ImageIcon icon_open=new ImageIcon("imgs/folder_open.gif");
              Action action_open=new AbstractAction("Open...",icon_open)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        openDocument();
              JMenuItem item_open=new JMenuItem(action_open);
              item_open.setMnemonic('o');
              item_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
              menu_file.add(item_open);
              JButton button_open=hm_toolBar.add(action_open);
              ImageIcon icon_save=new ImageIcon("imgs/floppy.gif");
              Action action_save=new AbstractAction("Save",icon_save)
                   public void actionPerformed(ActionEvent evt)
                        saveAs(false);
              JMenuItem item_save=new JMenuItem(action_save);
              item_save.setMnemonic('s');
              item_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
              menu_file.add(item_save);
              JButton button_save=hm_toolBar.add(action_save);
              Action action_saveAs=new AbstractAction("Save As...")
                   public void actionPerformed(ActionEvent evt)
                        saveAs(true);
              JMenuItem item_saveAs=new JMenuItem(action_saveAs);
              item_saveAs.setMnemonic('a');
              item_saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
              menu_file.add(item_saveAs);
              menu_file.addSeparator();
              Action action_close=new AbstractAction("Quit")
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              JMenuItem item_exit=new JMenuItem(action_close);
              item_exit.setMnemonic('q');
              item_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
              menu_file.add(item_exit);
              hm_menuBar.add(menu_file);
              setJMenuBar(hm_menuBar);
              getContentPane().add(hm_toolBar,BorderLayout.NORTH);
         protected String getDocumentName()
              return current_file==null ? "Untitled" : current_file.getName();
         protected void newDocument()
              html_document=(HTMLDocument)html_kit.createDefaultDocument();
              hm_styleSheet=html_document.getStyleSheet();
              hm_textPane.setDocument(html_document);
              current_file=null;
              setTitle(getDocumentName()+" - "+APP_NAME);
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected void openDocument()
              if(hm_fileChooser.showOpenDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                   return;
              File f=hm_fileChooser.getSelectedFile();
              if(f==null || !f.isFile())
                   return;
              current_file=f;
              setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   InputStream in=new FileInputStream(current_file);
                   html_document=(HTMLDocument)html_kit.createDefaultDocument();
                   html_kit.read(in,html_document,0);
                   hm_styleSheet=html_document.getStyleSheet();
                   hm_textPane.setDocument(html_document);
                   in.close();
              }catch(Exception ex)
                   showError(ex,"Error openning file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected boolean saveAs(boolean as)
              if(!as && !text_changed)
                   return true;
              if(as || current_file==null)
                   if(hm_fileChooser.showSaveDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                        return false;
                   File f=hm_fileChooser.getSelectedFile();
                   if(f==null || !f.isFile())
                        return false;
                   current_file=f;
                   setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   OutputStream out=new FileOutputStream(current_file);
                   html_kit.write(out,html_document,0,html_document.getLength());
                   out.close();
              }catch(Exception ex)
                   showError(ex,"Error saving file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              return true;
         protected boolean promptToSave()
              if(!text_changed)
                   return true;
              int result=JOptionPane.showConfirmDialog(this,"Save change to "+getDocumentName(),APP_NAME,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
              switch(result)
                   case JOptionPane.YES_OPTION:
                        if(!saveAs(false))
                             return false;
                        return true;
                   case JOptionPane.NO_OPTION:
                        return true;
                   case JOptionPane.CANCEL_OPTION:
                        return false;
              return true;
         protected void showError(Exception ex,String message)
              ex.printStackTrace();
              JOptionPane.showMessageDialog(this,message,APP_NAME,JOptionPane.WARNING_MESSAGE);
         public static void main(String[] args)
              new HTMLMagician();
         class action_textChanged implements DocumentListener
              public void changedUpdate(DocumentEvent evt)
                   text_changed=true;
              public void insertUpdate(DocumentEvent evt)
                   text_changed=true;
              public void removeUpdate(DocumentEvent evt)
                   text_changed=true;
    when i open a .html file,the command output :
    javax.swing.text.ChangedCharSetException
         at javax.swing.text.html.parser.DocumentParser.handleEmptyTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.startTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
         at javax.swing.text.html.parser.Parser.parse(Unknown Source)
         at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
         at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
         at javax.swing.text.html.HTMLEditorKit.read(Unknown Source)
         at javax.swing.text.DefaultEditorKit.read(Unknown Source)
         at HTMLMagician.openDocument(HTMLMagician.java:222)
         at HTMLMagician$4.actionPerformed(HTMLMagician.java:128)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    why? what's wrong? thanks

    The DocumentParser seems to throw a ChangedCharSetException if it finds a "http-equiv" meta tag for "content-type" or "charset" and if the parser's "ignoreCharSet" property is set to false on creation.

  • Fix for PENDING in javax.swing.text.html.ParagraphView line #131

    Investigating source of HTMLEditorKit I found many PENDING things. That's fix for one of them - proper minimal necessary span detecting in table cells.
    Hope it will help to somebody else.
    import javax.swing.*;
    import javax.swing.text.html.*;
    import javax.swing.text.html.ParagraphView;
    import javax.swing.text.*;
    import java.awt.*;
    import java.text.*;
    import java.util.ArrayList;
    public class App extends JFrame {
        public static String htmlString="<html>\n" +
                "<body>\n" +
                "<p>The following table is used to illustrate the PENDING in javax.swing.text.html.ParagraphView line #131 fix.</p>\n" +
                "<table cellspacing=\"0\" border=\"1\" width=\"50%\" cellpadding=\"3\">\n" +
                "<tr>\n" +
                "<td>\n" +
                "<p>111111111111111111111111111111111<b>bold</b>22222222222222222222222222222</p>\n" +
                "</td>\n" +
                "<td>\n" +
                "<p>-</p>\n" +
                "</td>\n" +
                "</tr>\n" +
                "</table>\n" +
                "<p></p>\n" +
                "</body>\n" +
                "</html>";
        JEditorPane editor=new JEditorPane();
        JEditorPane editor2=new JEditorPane();
        public static void main(String[] args) {
            App app = new App();
            app.setVisible(true);
        public App() {
            super("HTML span fix example");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JSplitPane split=new JSplitPane(JSplitPane.VERTICAL_SPLIT, createFixedPanel(), createOriginalPanel());
            getContentPane().add(split);
            setSize(700, 500);
            split.setDividerLocation(240);
            setLocationRelativeTo(null);
        JComponent createOriginalPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Original HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new HTMLEditorKit();
            editor2.setEditorKit(kit);
            editor2.setContentType("text/html");
            editor2.setText(htmlString);
            p.add(new JScrollPane(editor2), BorderLayout.CENTER);
            return p;
        JComponent createFixedPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Fixed HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new MyHTMLEditorKit();
            editor.setEditorKit(kit);
            editor.setContentType("text/html");
            editor.setText(htmlString);
            p.add(new JScrollPane(editor), BorderLayout.CENTER);
            return p;
    class MyHTMLEditorKit extends HTMLEditorKit {
        ViewFactory defaultFactory=new MyHTMLFactory();
        public ViewFactory getViewFactory() {
            return defaultFactory;
    class MyHTMLFactory extends HTMLEditorKit.HTMLFactory {
        public View create(Element elem) {
            View v=super.create(elem);
            if (v instanceof ParagraphView) {
                v=new MyParagraphView(elem);
            return v;
    class MyParagraphView extends ParagraphView {
        public MyParagraphView(Element elem) {
            super(elem);
        protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
            r = super.calculateMinorAxisRequirements(axis, r);
            float min=getLongestWordSpan();
            r.minimum = Math.max(r.minimum, (int) min);
            return r;
        public float getLongestWordSpan() {
            if (getContainer()!=null && getContainer() instanceof JTextComponent) {
                try {
                    int offs=0;
                    JTextComponent c=(JTextComponent)getContainer();
                    Document doc=getDocument();
                    int start=getStartOffset();
                    int end=getEndOffset()-1; //don't need the last \n
                    String text=doc.getText(start, end - start);
                    if(text.length() > 1) {
                        BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
                        words.setText(text);
                        ArrayList<Integer> wordBounds=new ArrayList<Integer>();
                        wordBounds.add(offs);
                        int count=1;
                        while (offs<text.length() && words.isBoundary(offs)) {
                            offs=words.next(count);
                            wordBounds.add(offs);
                        float max=0;
                        for (int i=1; i<wordBounds.size(); i++) {
                            int wStart=wordBounds.get(i-1)+start;
                            int wEnd=wordBounds.get(i)+start;
                            float span=getLayoutSpan(wStart,wEnd);
                            if (span>max) {
                                max=span;
                        return max;
                } catch (BadLocationException e) {
                    e.printStackTrace();
            return 0;
        public float getLayoutSpan(int startOffset, int endOffset) {
            float res=0;
            try {
                Rectangle r=new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
                int startIndex= layoutPool.getViewIndex(startOffset,Position.Bias.Forward);
                int endIndex= layoutPool.getViewIndex(endOffset,Position.Bias.Forward);
                View startView=layoutPool.getView(startIndex);
                View endView=layoutPool.getView(endIndex);
                int x1=startView.modelToView(startOffset,r,Position.Bias.Forward).getBounds().x;
                int x2=endView.modelToView(endOffset,r,Position.Bias.Forward).getBounds().x;
                res=startView.getPreferredSpan(View.X_AXIS)-x1;
                for (int i=startIndex+1; i<endIndex; i++) {
                    res+=layoutPool.getView(i).getPreferredSpan(View.X_AXIS);
                res+=x2;
            } catch (BadLocationException e) {
                e.printStackTrace();
            return res;
    }Regards,
    Stas

    I'm changing the foreground color with
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, newColor);
    int start=MyJTextPane..getSelectionStart();
    int end=MyJTextPane.getSelectionEnd();
    if (start != end) {
    htmlDoc.setCharacterAttributes(start, end, attr, false);
    else {
    MutableAttributeSet inputAttributes =htmlEditorKit.getInputAttributes();
    inputAttributes.addAttributes(attr);   

  • Not able to highlight text. Help please?

    Hi I am trying to build a tool which is going to be used to to load an html book and the make some notes on it. Now I am trying to highlight. I am in thye very beginning so I just try to highlight a small part from the begginig not the user, this is my next step. But even I think that I don't have a problem with my code as I have used as base a program that is working actually my rpogram doesn't highlight anything.
    Here is the class I make the highlight
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.HashMap;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.undo.*;
    public class ViewClass extends JFrame {
      private JFrame frame = new JFrame(); // main window
      private JPanel panel = new JPanel(new BorderLayout()); //panels to aid layout
      private JPanel panel2 = new JPanel(new GridLayout(1, 1));
      private JMenuBar menuBar=new JMenuBar();
      JMenu file = new JMenu("File");
      JMenu help = new JMenu("Help");
      JMenuItem open=new JMenuItem("Open");
      JMenuItem save=new JMenuItem("Save");
      JMenuItem exit=new JMenuItem("Exit");
      JMenuItem manual=new JMenuItem("Manual");
      JMenuItem about=new JMenuItem("About");
      JButton buttonH=new JButton();
      JButton buttonB=new JButton();
      JButton buttonT=new JButton();
      private JToolBar toolBar = new JToolBar();
      private JScrollPane scrollPane = new JScrollPane();
      private Model callingModel;
      private Controller theController;
        private static JEditorPane createEditorPane() {
        JEditorPane editorPane = new JEditorPane();
        editorPane.setEditable(false);
        java.net.URL helpURL = ViewClass.class.getResource("mexico_city.html");
        System.out.println(helpURL);
        if (helpURL != null) {
            try {
                editorPane.setPage(helpURL);
            } catch (IOException e) {
                System.err.println("Attempted to read a bad URL: " + helpURL);
        } else {
            System.err.println("Couldn't find file: mexico_city.html");
         return editorPane;
    public ViewClass(Model m) {
         callingModel =m; //retrieve link to model
         theController = new Controller(callingModel); // create controller
         //set up visual features of the window
         frame.setTitle("Take a note");
         frame.setJMenuBar(menuBar);
         menuBar.add(file);
         menuBar.add(help);
         file.add(open);
         file.add(save);
         file.addSeparator();
         file.add(exit);
         help.add(manual);
         help.add(about);
         file.setMnemonic(KeyEvent.VK_F);
         help.setMnemonic(KeyEvent.VK_H);
         //frame.getContentPane().setLayout(new BorderLayout());
         toolBar.add(buttonH);
         buttonH.setIcon(new ImageIcon("H.gif"));
         buttonH.setToolTipText("Highlight");
         buttonH.setActionCommand("Highlight");
         toolBar.add(buttonB);
         buttonB.setIcon(new ImageIcon("B.gif"));
         buttonB.setToolTipText("Bookmark");
         buttonB.setActionCommand("Bookmark");
         toolBar.add(buttonT);
         buttonT.setIcon(new ImageIcon("T.gif"));
         buttonT.setToolTipText("Take a note");
         buttonT.setActionCommand("Noting");
         JEditorPane editorPane = createEditorPane();
         scrollPane = new JScrollPane(editorPane);
         MyHighlightPainter h = new MyHighlightPainter(Color.yellow);
         Highlighter hilite = editorPane.getHighlighter();
         try
              hilite.addHighlight(155, 1155,h);
         catch(BadLocationException ex)
              System.out.println(ex.getMessage());
        frame.getContentPane().add(panel);
        frame.getContentPane().add(panel2);
        panel.add(toolBar, BorderLayout.PAGE_START);
        panel.add(scrollPane, BorderLayout.CENTER);
       frame.getContentPane().add(panel, BorderLayout.CENTER);
       panel.add(new JScrollPane(editorPane) );
       exit.addActionListener(theController);
       about.addActionListener(theController);
       buttonH.addActionListener(theController);
       buttonB.addActionListener(theController);
       buttonT.addActionListener(theController);
         //ensure the following statement is always last
         frame.pack();
         frame.setSize(1274,970);
         frame.setVisible(true);//and nobody sees it until we do this
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       static class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
    public MyHighlightPainter(Color r)
    super(r);
    }

    With interactive reports in APEX 3.1 you can use the pull down menu to highlight cells and or rows of data. You can apply many highlighting rules, that are evaluated in order. So high values can be green, low values red, and other values default. You can try this running the sample application on OTN:
    http://apex.oracle.com/pls/otn/f?p=2357:2
    Mike

  • Can't print text documents

    For a little over a week I have been unable to print text documents from either of my printers (Lexmark Z-23 and HP PSC 1410). I had noticed that the sharpness of text had been declining-but I was in denial, sort of. Now, when printing text documents from the computer, the printout is garbled, streaked, and unreadable. Sometimes the first half of printed document will be okay but the second half will be all garbled and streaked.
    I have tried to print from Pages, Appleworks, and TextEdit. No success in any of them. I have converted a page of my word processing document to pdf format, but it does not print out properly in pdf, either.
    Here's the weird part: the HP will produce good copies (copy function) I am able to print out beautiful iCal (calendar) pages; some web-based information (like maps with directions) comes out great; and even "screen-shots" (or pictures) of text documents are fine; I just can't print text-based documents.
    So far, I have cleaned and calibrated the printers; they have enough ink. I have uninstalled then reinstalled the software and drivers.
    Help?
    ~~PM
    iMac G5 2GHz PPC   Mac OS X (10.4.8)   still miss my Indigo G3

    my guess is, it's not your printers that are the
    problem but maybe a font problem.
    Have you done anything with fonts lately?
    Why, yes.
    Just today, in FontBook I validated fonts and
    resolved duplicates, whatever that means. I also
    "turned off" a bunch of fonts that I never use. Then
    I restarted, reset PRAM, and repaired permissions in
    Disk Utility.
    I still have the problem.
    What other kinds of things can you do with fonts?
    ~PM, wife of GM
    Glenn-- Here is a great article written by a fellow apple forum frequenter:
    http://www.jklstudios.com/misc/osxfonts.html
    Maybe you can read it or weed thru it and make sure you haven't turned off any necessary fonts that you don't use but the system finds necessary. Especially "TextEdit" uses I think exclusively system fonts and if you've turned them off... It's just good to know which fonts are for what before you disable certain ones.
    I believe fonts can definitely cause these sorts of problems, especially if you've disabled system fonts.

  • How do I remove a green background from a pdf text document?

    I posted this question yesterday and received one reply.  I wanted to respond to the reply, but couldn't find a link or "button" to click on that would enable me to do that, so I'm doing it here.  As I'm new to this site, please advise me where the link is, if there is one. 
    Please correct me if I'm wrong, but I thought that PDF was proprietary, with one "owner" and that PDF was PDF, so it didn't matter what program you had on your computer because PDF was universal.  Second, when I googled Nuance pdf, I was directed to this site, specifically the "Create, Edit and Export PDF's" section.  Third, I also have Adobe Acrobat with pdf and a bunch ofother Adobe products on my computer.  So, that brings me back to my original question,  how do I get rid of a green background on a pdf text document, so I don't use up all my ink when I print it.  Thanks for your patience and help.

    I still use Office 2008 but have not encountered that issue. However, as Office is not an Apple product, I strongly recommend asking in the Microsoft Office:Mac forums here:
    Office for Mac
    Everyone there is a Mac user AND an Office user, something you can't say about Apple's forums. You will get the fastest help there and I think you will find the contributors more than helpful.

  • Hi, i'm new in my macbook air! i miss deleted my external hard disk few day ago and i had spend 45GBP to recovery the data! but the problem now is the text document is locked i not even can read and open the document! any solution??? urgent

    hi, i'm new in macbook air, i was miss formatted and delete all my data on my external hard disk (pic, microsoft office document and etc). i spend 45gbp to install the software fianlly recovery all the data! but why my text document can't open and read?? what's is the problem?? because i'm still a student i hv alot of assignment file cant be read and open but nect week is the deadline of submission and i have no back up of all document. So any useful suggetion solution?? i've try the way alt+command+i to unlock but it doesn't work!! help! URGENT

    when i open the file it appear some digits and word tat i couldn't understand. and the tool bar stated "Locked"
    example: 422583321135679999=@ABBCCEEFGHIKJHMIFFFHFHDCEGFFBI\cb[C?@<=>=;;;<;>>>?<>B@>?==< =>?>@A?>?@<==<;:::899:89>:9;99;9:;<;66988;359<==9987789:8::9;>>=799<>:88856::;<: 99====<::98988;;96677998887866:89::;99647878665797698899;8466646763/121120+031/1 2/.1.,.0//.+/,+.0220/0.-/21-++--1---+-.+-.--/=Pdoxx
    the digits and words tat appear on my document!
    i used MiniTool Mac data to recovery! actually b4 tat i'm using hp computer and i saved all my files in my external hard disk. When i using mac i installed the NTFS-3G but it still cant read my external hard disk and i miss deleted and formatted all the data in my external hard disk. after tat my friends suggest me to purchased the software to recover all the data,finally i got all my photo back except my microsoft office files.
    i purchased miscrosoft office software for my mac yesterday but the files still cant be read and couldnt recover back the document tat i saved! i was upset to spent alot of money but still cant get my document back!!

  • How can you detect all words and phrases in a text document using java?

    Is there some java API which would help me extract all words, multi-word phrases, punctuations in an English text document? I would also like to get the order in which they appear with sentence detection. I've been searching for this in java NLP packages, but haven't found anything yet.
    Any help would be appreciated.
    Thanks,
    Ajith

    I don't understand what you actually want, but if your on about having a file and splitting it up into sentences then i would look into either psudocode or parsing strings, theres not a java api as far as i know that does anything like you want, you would have to write it yourself or find a project someone else has made.

Maybe you are looking for

  • MSComDlg.ICommonDialog Problem with Windows 64-bit system

    Hi all! I try to use the common Windows dialog box for saving files. For this I'm using the ActiveX-class "MSComDlg.ICommonDialog" with the propertynode input "Filter" for the file types. It's the standard "SaveAsType.vi" (somewhere in the forum). Ev

  • AirtPort is not listed as one of Network choices in System Prefs

    I'm trying to set up a WiFi connection/network (using 2 G5 Macs and AirPort Extreme). All online instructions start with "...select AirPort in System Network Preferences.." In my Preferences it doesn't show up. All I got there are two Ethernets and F

  • When you buy a buy at the itunes store do you get access to closed caption on like a DVD

    I would like to know if the movies you purchase from the Itunes store allows you to have closed caption.  We have purchased a lot of amazon but the closed caption is not an option there and we would love to switch over to Itunes for movies.

  • Gift card usage

    I am looking for how to use a gift card in the itunes store. I have an acocunt already, and have no problem purchasing songs with a credit card, but do not see anywhere to enter in the gift card. I looked at help and it says it should be in the accou

  • App Store "Cannot quit while updates are in progress."

    I just upgraded and am trying to update the Apple branded applications, but the process has stopped at 1 minute remaining and won't proceed.  I can't quit the App Store app, and therefore can't reboot either.  I will probably just force-quit, but I'm