JEditorPane: transforming between caret position in html and text/plain

Hi all,
I've done quite a bit of searching, and found problems similar to this one, but not this exactly, so I'll try asking it here.
I have a JEditorPane with HTMLEditorKit, which I'm using for a WYSIWYG text editor. When the user wants to insert something, say an image, I get the caret position and insert a String into the document's underlying text.
The problem is that if we are the WYSIWYG mode, the caret position isn't the same as the caret position in text/plaain mode.
So if the underlying text is
<html>
  <body>
     Some text
  </body>
</html>the user will just see "Some text". If they place the caret between "Some" and "text", editorPane.getSelectionStart() will return '5'. But I want to insert my text at position '16' in the plain text.
Is there a simple way to go back and forth between these two positions? Or to have getSelectionStart() to return the index relative to the text/plain mode?
Thanks!
Tim

Very poor that no one answered this one.
Did you still need the answer?
I have 'a' answer. But not a complete one.
In fact I only found this in search for an answer for my problem:
http://forums.sun.com/thread.jspa?threadID=5409216&tstart=0
Did you actually just test out what you knew so far to test what happens?
If you were to use the HTMLEditorKit.insertHTML function, it just wants the visual caret position. So '5' would have been reasonably correct for you.
I was doing something like this:
               HTML.Tag tag = null;
               Pattern p = Pattern.compile("\\s*\\<\\s*(\\w+).*", Pattern.MULTILINE|Pattern.DOTALL);
               Matcher m = p.matcher(text);
               if (m.matches())
                    tag = HTML.getTag(m.group(1));
               kit.insertHTML(doc, offset,// +1
                              text, 0,// 0
                              0,// 0
                              tag);
Assuming you were inserting a tag, my code there checks what tag it is, and if that is known by the java implementation, assigns that to 'tag', so that the element is correctly inserted.
If it is not known, we just use 'null'. Which for me wasn't such a great result.
In fact, nothing really was a great result, as with the default java implementation being buggy (so far as I can see) it inserted to the wrong position and caused all sorts of anomalies.
Hope you worked it out. And if you did, and have a better result than what I have, maybe you can let me know what you did!
Sincerely,
sean

Similar Messages

  • Getting caret position in HTML of JEditorPane

    Hi
    How can I get the equivalent position of the caret in the HTML behind a JEditorPane?
    Regards
    Peter

    Do you mean how to take the int that is returned from
    editorPane.getCaretPosition();
    and figure out what HTML is at that position?
    HTMLEditorKit (javax.swing.text.html) may help. Also check out class HTMLDocument and its method getReader(int pos).
    Sorry, I haven't actually done this, so I am just throwing out ideas.
    Barb

  • Caret position in HTML JTextPane

    Hi all,
    This question has been asked before, but with no satisfying answer that I can find so, in the hope that the eyes of a Swing text expert will fall upon this post, I'm having to ask again...
    Is there a simple means of translating the current caret position within a JTextPane to the offset within the HTML code it represents?
    In other words, where the JTextPane displays:Now is the time...The underlying HTML might be:<html><head></head><body><p align="left">Now is the time...</p></body></html>With the cursor positioned just in front of 'is', the caret position would be 4, but in the underlying HTML, the position would be 46.
    Any ideas, hints, suggestions or complete answers appreciated!
    Chris.

    I would suggest a trick.
    Suppose you ave actul caret position in JEditorPane.
    int caretPos=...;
    use HTLEditorKit.write(someWriter,htmlDoc,0,caretPos);
    Then you'll have a string
    <html><head></head><body><p align="left">Now </p></body></html>
    Then throw away all the closing tags and you'll have what you need by string length.
    Of course you would have to write kind of converter to clear out all formatting chars.
    regards,
    Stas

  • Email attachment and text/plain

    Well, the Mail app on iPhone really needs improvement.
    I've got my iPhone for 4 days only, and I already have 3 things (at least) that IMHO need to be improved:
    1. Someone forwarded me an email, and that email now appears as an .eml attachment, which iPhone seems to be incapable to handle.
    2. I friend of mine sent me an email that iPhone is unable to display at all. I get the error message like "Mail does not know how to display text/plain" -- come on guys at apple! Only a few years ago plain text (i.e., ASCII) was the only format! And it is the most easiest to display! ...
    3. Spam - the iPhone should have the same spam filter than Mail on my laptop. Oh, and the same rules and folders I have on my laptop, please!
    I hope apple is reading this.
    Regards,
    Gabriel.

    inbedded is not a word.

  • Conditional Formula between Check Box, Combo Box and Text Field

    I am very new in this area and just trying to figure out things here. Anyway, what I am trying to do is quite straight forward. I have a TextField, which the content is depending on what being selected in the CheckBox and ComboBox. The TextField shall give the value of the membership fee depending either he is Local or Abroad (CheckBox) and depending on Age Categories (ComboBox). Could you please help me in getting the script? Really appreciate it and thanks a lot in advance.

    hi gilad,
    tried your code already and and changed accordingly to mine:
    event.value = "";
    var type = this.getField("NatKid1").value;
    var age = this.getField("AgeKid1").value;
    if (type=="Yes") {
        if (age=="1")
    event.value = 0;
        else if (age=="2")
    event.value = 1;
        else if (age=="3")
    event.value = 3;
    } else if (type=="No") {
        if (age=="1")
    event.value = 0;
        else if (age=="2")
    event.value = 1.5;
        else if (age=="3")
    event.value = 4;
    and it works!!! still doing some trial run on some devices/gadgets and shall let you know. thanks again, gilad

  • Position an image and text on a button

    Hi ,
    I would like to customize my button to put text and icon on it. I do the following :
    <mx:Button width="120"   icon="myIcon"   label="Actu suivante"   styleName="actualiteButton"/>
    The problem is that I like to put the text first in  the left followed by icon on the right , How can I do this ;
    Regards.

    Ok thank's for your help
    2009/9/10 babo_ya <[email protected]>
    labelPlacement="left" or labelPlacement="right"
    >
    hope this helps,
    >
    BaBo,
    >

  • Find caret position of search text in jEditorPane

    Hi All,
    I am looking for a way to find the Caret position in a jeditor pane for the search text that i supply. The Jeditor pain is setup for text/html and when i find the index of my search text "ANCHOR_d" in the jeditor pane is 27000 something but the caret position is 7495 how do you find the caret position of the search text ??
    Any help is appriciated.
    I am also looking into getting abnchoring to work in the jeditorpane html text but as of yet i have been unsuccessful.
    Kind Regards,
    Wurns

    Search the underlying document, not the editor pane. Play around with this example, which I threw together the other day for a somewhat similar problem with JTextPane involving newlines, and modified for your need.
    Note: Please do not program by exception.import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.Document;
    public class SearchEditorPane {
       JFrame frame = new JFrame ("Search JTextPane Test");
       String html = "<HTML><BODY><P>This is <B>some</B>" +
                    " <I>formatted</I>" +
                    " <FONT color=#ff0000>colored</FONT>" +
                    " html.</P>" +
                    "<P>This is a <FONT face=Comic Sans MS>" +
                    "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                    "And this is a new division</div>" +
                    "</BODY></HTML>";
       JEditorPane editorPane = new JEditorPane ("text/html", html);
       JPanel panel = new JPanel ();
       JTextField textField = new JTextField (10);
       JButton button = new JButton ("Find");
       Document doc = editorPane.getDocument ();
       void makeUI () {
          editorPane.setText ("<HTML><BODY><P>This is <B>some</B>" +
                " <I>formatted</I>" +
                " <FONT color=#ff0000>colored</FONT>" +
                " html.</P>" +
                "<P>This is a <FONT face=Comic Sans MS>" +
                "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                "And this is a new division</div>" +
                "</BODY></HTML>");
          button.addActionListener (new ActionListener () {
             public void actionPerformed (ActionEvent e) {
                // Programming by exception is BAD, don't copy this style
                // This is just to illustrate the solution to the problem at hand
                // (Sorry, uncle-alice, haven't reworked it yet)
                try {
                   Matcher matcher = Pattern.compile (textField.getText ())
                   .matcher (doc.getText (0, doc.getLength ()));
                   matcher.find ();
                   editorPane.setCaretPosition (matcher.start ());
                   editorPane.moveCaretPosition (matcher.end ());
                   editorPane.requestFocus ();
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog (frame, "Not Found!\n" + ex.toString ());
                   //ex.printStackTrace();
          panel.add (textField);
          panel.add (button);
          panel.setPreferredSize (new Dimension (300, 40));
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 300);
          frame.add (editorPane, BorderLayout.CENTER);
          frame.add (panel, BorderLayout.SOUTH);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new SearchEditorPane ().makeUI ();
    }db

  • How to get the caret position of component embedded in JTextPane?

    Hi great java developers ;-)
    I want to get the caret position of component which is embedded in StyledDocument / JTextPane.
    How has it to be done?
    Thank you very much!!!

    The Document doesn't know which textPane it belongs to. (It could even be shared by mulitple textPanes).
    You get the caret position of a any text component by using:
    textComponent.getCaretPosition();

  • Html and CSS in JEditorPane

    I have been working with Velocity to produce dynamic HTML and displaying the results with the JEditorPane. I have been searching for an article or tutorial that talks about the JEditorPane (HTML and CSS related), but nothing has come up (I also did a quick search in this forum).
    I would like to know what is JEditorPane capable of doing in terms of displaying HTML with CSS, and how do you set it up.
    If JEditorPane is not the best option with HTML that has positioning in CSS, can somebody suggest something else that has better support for CSS than JEditorPane?
    I would greatly appreciate any response (Any suggestion or links to additional information will be great too!)
    Thanks,
    Victor Gutierrez

    I would like to know what is JEditorPane capable of
    doing in terms of displaying HTML with CSS, and how
    do you set it up. JEditorPane has no support for CSS
    If JEditorPane is not the best option with HTML thatit's not
    has positioning in CSS, can somebody suggest
    something else that has better support for CSS than
    JEditorPane?Search google for 'JDIC' find the WebBrowser component
    I would greatly appreciate any response (Anylet's not get carried away here
    suggestion or links to additional information will be
    great too!)
    Thanks,
    Victor Gutierrez

  • WebView / HTMLEditor - caret position and selected content

    Hey :)
    Is it possible to get the caret position and the selected content in the HTMLEditor / WebView? How?
    Thanks in advance.

    Use JavaScript methods. For example:
    http://stackoverflow.com/questions/9370197/caret-position-cross-browser
    http://stackoverflow.com/questions/6129006/get-the-raw-html-of-selected-content-using-javascript
    Use the Java\JavaScript bridge if you want the result in Java:
    http://docs.oracle.com/javafx/2/webview/jfxpub-webview.htm

  • Regarding connection between front end HTML and back end SQL 7.0

    Hi!!
    I am working on the project 'ERM'. I have designed 12 forms using HTML. Can u please give me brief idea how to establish the connection between a back end and front end i.e. between HTML and SQL 7.0. If possible can u provide me the source code for the same.
    I will be very thankful to you.
    Thanks,
    Jigar.

    Read up about multi-tier applications.
    You need servlet and JSPs for the server-side presentation layer, some classes for the business logic, and some mor for the persistence layer either using JDBC or some framework like Hibernate.

  • Transformation between DS and DSO missing Non-cumulative KYF

    Hi SDN,
    I installed the business content for CML, and am working with 0CML_DELTA_CAP datasource.  I would like to create a transformation between this datasource and DSO 0CML_O03.
    By default, when you install the CML business content, the datasources use the 3.x dataflow concept (transfer rules, infosources, and update rules).
    I would like to use the 7.x dataflow concept and created a transformation between the 0CML_DELTA_CAP datasource and the 0CML_O03 DSO.  In the transformation, it is missing the fields 0CML_B330, 0CML_B340, 0CML_B360, 0CML_B380 in the datatarget.  These key figures are non-cumulative with NCum Value change (0CML_B330 uses 0CML_B331 as value change).  The value change key figures show up in the transformation, but the non-culmulative key figures do not. 
    Does anyone have any ideas why the non-cuml. kyf are not showing up in the transformation?
    Thanks,

    Hi Brendon,
    The non- cumulative key figures are not mapped in the transformation. Only the 'Inflow' and 'Outflow' key figures for the non- cumulative key figure are mapped.
    You can check the property for the non- *** KF in RSD1, where you would find the corresponding inflow and outflow kf. If both of these are mapped in the transformation, the non- *** kf would calculate the value in the report in which it is included as:
    Non-*** KF value = Inflow value - Outflow value.
    Hope this helps.
    Regards,
    Abhishek.

  • Is the transformation between XML document and 2 dimensions table important?

    To everyone:
    I am trying to write a paper on this topic.first ,i want to ask whether the transformation between XML data and table in RDBMS is important,because xml data is suitable to transfer from a point to another,but not for storage,so when the transfer begin a program(in DB2,the program is DB2 extender)should change the data format in table into a xml document.And vice versa,the destination point receive the xml document,maybe the same program would store it in table.
    so i wonder if such a program exists in the Oracle8i or later version,and the detail about how the program realizes above funciton.please tell me where can i find related paper or materials.
    thanks!

    To everyone:
    I am trying to write a paper on this topic.first ,i want to ask whether the transformation between XML data and table in RDBMS is important,because xml data is suitable to transfer from a point to another,but not for storage,so when the transfer begin a program(in DB2,the program is DB2 extender)should change the data format in table into a xml document.And vice versa,the destination point receive the xml document,maybe the same program would store it in table.
    so i wonder if such a program exists in the Oracle8i or later version,and the detail about how the program realizes above funciton.please tell me where can i find related paper or materials.
    thanks! That is all oracle XDK is for. You can transform query results to xml and xml back into RDBMS. Infact Oracle provides much more flexible way than a DB2 extender does. In DB2 you need to give a DAD before you get any XML. Oracle relies on the direct transformation of query results into XML and adds flexibility of XSL ontop of the data.
    You can get more information on XML technology section of OTN.
    Once you write the article can we get a chance to see it.

  • I cannot transform between Arabic and English language in writing

    I cannot transform between Arabic and English language in writing >>>> I should every time restart my browser >>>> i need a solution

    If you are talking about typing text then make sure that the language toolbar is visible.
    * http://windows.microsoft.com/en-US/windows7/The-Language-bar-overview
    In Firefox you can switch the bidi text direction via Ctrl+Shift+X.

  • How to listen and obtain caret positions of changed text in JTextPane?

    Hi,
    I have a JTextPane that displays text with some styles on particular words in the text. For example, I highlight words with red color if they are in my dictionary file. I use regular expression to find matches, replace them with their corresponded definitions, and call setCharacterAttributes to add styles to the definitions. I store all start and end caret positions of the matched words/definitions in a vector. So, I can redisplay styles of all previous matches.
    The problem is that I'd like to be able to edit the text of some previous matches. So, with those changes all caret positions that I already store in the vector need to be updated.
    How can I obtain caret positions of changed text in JTextPane?
    How can I know that a user is currently changing text in the JTextPane?
    How can I get style of text such as color that is being changed?
    Thank you very much.

    Thank you very much, camickr, for your reply.
    I think that I might not know the right way to handle JTextPane and Document object.
    What I have done are:
    - Add style to JTextPane using, for example,
    Style targetCurrentMatchStyle = this.targetWindowTextPane.addStyle("Red", null);
    StyleConstants.setForeground(targetCurrentMatchStyle, Color.red);//For highlight - Then, I use regular expression (Pattern and Matcher) to find a match in text. For each match, I get start and end position from matcher.start() and matcher.end().
    if(matcher.find(start)){
    String term=matcher.group();
    int start=matcher.start();
    int end = matcher.end();
    //find definition for the matched term.
    String definition=mydictionaryHash.get(term);
    //Store caret positions in lists
    startPositionList.add(start);
    matchedLength=lengthList.add(definition.length());
    //Add changed to text in textpane
    StringBuffer sb=new StringBuffer();
    matcher.appendReplacement(sb, definition);
    matcher.appendTail(sb);
    //Get translated text from StringBuffer after replacement
    String translatedText=sb.toString();
    targetWindoTextPane.setText(translatedText);
    //Update start position for next search
    start=start+definition.length();
    //Add style to matched regions below.
    }- From the lists of start positions and matched lengths, I use the following code to add "Red" color to the matched text regions including all previously matched.
    for(int i=0;i<startPositionList.size();i++){
    this.targetWindowTextPane.getStyledDocument().setCharacterAttributes(
    startPositionList.get(i),
    lengthList.get(i),
    this.targetWindowTextPane.getStyle("Red"),
    true);
    }My issue is that I'd like to be able edit previously matched regions and update all positions of the matched regions stored in the lists.

Maybe you are looking for