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.

Similar Messages

  • 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();

  • How to get the current caret position of a field

    I would like to mimic a feature known from some UI parts in Eclipse (especially launch configurations) - inserting a predefined variable. It allows to modify the value of a text field by inserting a special value to the position of the caret.
    I'm struggling with how to get the caret position in Sapphire since the model does not propagate such UI-specific info. Is there a way how to implement this which does not involve creating a special field implementation?
    Thanks in advance.

    Sorry for the delay in responding. Currently, there is no API available to implement what you are describing. We should add a TextSelectionService similar to the existing ListSelectionService.

  • Detecting key events and setting caret position from a Document model

    Hello, I have created a "masked" JTextField that contains specific formatting (these subclasses were created prior to the advent of Sun's implementation of masked fields, and are used extensively throughout my system, so I can't easily implement Sun's version at this time)
    At any rate, here is the problem:
    Consider the following "masked" field contents (date USA format):
    The user keyboard input is:
    "10252002", which results in the text field display of "10/25/2002"
    The user presses the "delete" key in the first position of the masked field. The following result is "0/25/2002".
    This is undesirable, since all the contents of the field have shifted to the left by one position, so the first "/" is now in position 2, instead of position 3. Also, the length of the field is now 9, instead of 10.
    The field should really have the following contents: "02/52/002_", and the cursor should remain on the first position of the text field.
    I believe need for the Document model to be able to differentiate between a "back space", and a "delete", so that my overridden "remove" method in my PlainDocument subclass can handle
    insertion/repositioning of "masked literal" characters correctly, and also control the cursor movement accordingly.
    What would be the best way to handle this?

    I would re-post to the Flex Data Services forum.

  • How to cut and paste long Word document into text generator?

    I have a very long list of attributions in a Word document.
    When I cut and paste it into the "Sample Text" area, it goes in fine.
    But when I try to look at it ... either as simple text or, preferred, scrolling ... I only get parts of the document.
    I can correct it by adding a 'return' in the middle of every few words.
    But my document is so long, it would take a long time to do that one by one.
    Solutions sought: How to just import the whole document and have it scroll, zip-zip?!

    Thank you DH and skalaki, I had not known of the Boris title generator. Funny, I had looked in the FCE online manual until 'titling' and editing text ... didn't see mention of that.
    In any case ... I've now found it and trust I'll be able to figure it out.
    Since skalaki was first with the answer, I awarded the 'solved' there. DH's comments were further helpful.

  • Robot class and obtaining mouse position

    The Robot class has the mouseMove(int x, int y) method which allows you to position the mouse at the given x-y coordinates. I am trying to move the mouse using relative coordinates, i.e. move 200 pixels left, as opposed to moving to 400,800. Is there a way to obtain my cursor's current position? I've looked at the MouseEvent class, and I'm not very sure that would work, as it requires input from the mouse in order to trigger.

    TryPointerInfo pointerInfo = MouseInfo.getPointerInfo();
    Point p = pointerInfo.getLocation();

  • Text field highlight problem after caret position is set

    Hi,
    What I am trying to do is: set caret position and then highlight the text after it. The problem is: if I set caret position first, and highlight the rest of the text, the caret position is then set at the end of the entire text; if I highlight text first, and set caret position, then the text is not highlighted.
    I am wondering how I can achieve this. Thanks.
    The simple test program is below:
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class TestTextFieldHighlight {
         public static void main(String[] args) {
             JFrame f = new JFrame("Text Field Examples");
             f.getContentPane().setLayout(new FlowLayout());
             JTextField tf = new JTextField("SampleTextField", 20);
             tf.setEditable(true);
             f.getContentPane().add(tf);
             tf.setCaretPosition( 5 );
            tf.setSelectionStart( 6 );
            tf.setSelectionEnd( tf.getText().length() );
            //tf.setCaretPosition( 5 );
             f.pack();
             f.setVisible(true);
    }

          //tf.setCaretPosition( 5 );
          tf.setCaretPosition( tf.getDocument().getLength() );
          tf.moveCaretPosition(6);
          //tf.setSelectionStart( 6 );
          //tf.setSelectionEnd( tf.getText().length() );

  • Setting Caret Position

    Dears,
    How do I set the Caret position to a required position in the SpinnerNumberModel? Do I need to use setDot() and NavigationFilter? The position should be set as soon as Spinner is constructed.
    Please help.
    Thanks,
    Raj

    Hi,
    I didn't get it work too, but this workaround seems to work.
    Cheers
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    public class CaretPositioner extends Application {
         public static void main(String[] args) {
              Application.launch((java.lang.String[]) null);
         @Override
         public void start(Stage primaryStage) {
              BorderPane root = new BorderPane();
              final TextField tf = new TextField();
              tf.textProperty().addListener(new ChangeListener<String>() {
                   @Override
                   public void changed(ObservableValue<? extends String> arg0, String arg1, String arg2) {
                        System.out.println(tf.getCaretPosition());
                        Platform.runLater(new Runnable() {
                             @Override
                             public void run() {
                                  tf.positionCaret(0);
              root.setCenter(tf);
              Scene scene = new Scene(root);
              primaryStage.setScene(scene);
              primaryStage.show();
    }

  • Set the exact position of a text or variable

    Dear All !
    How can I set the exact position of a text (absolute) in SAPScript
    like "write" command's positional possibility.
    e.g
    WRITE: /3 'Name', 15 , 30 'RoomNo', 45 'Age'.
    Regards
    Ilhan

    Hi,
    WRITE: /3  'Name', 15 'XXX' , 30  'RoomNo', 45  'Age'.
    This will work.......
    Check out........
    Regards,
    Priyanka.

  • How to update caret position in status bar ?

    Hello, I'm trying to display 'Line Number & Position' in my status bar, I'm not sure how to proceed from here.
    How would I update this to occur on every keystroke?
    SSCCE
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.KeyEvent;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.border.EtchedBorder;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Element;
    import javax.swing.text.Utilities;
    public class test extends JFrame
         private static final long serialVersionUID = 1L;
         private JTextPane pane;
         @SuppressWarnings("unused")
         public static void main(String[] args)
              test t = new test();
         public test()
              super("test");
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setLayout(new BorderLayout());
              this.add(textPane(), BorderLayout.CENTER);
              this.add(statusBar(), BorderLayout.SOUTH);
              this.pack();
              this.setVisible(true);
         private JTabbedPane textPane()
              pane = new JTextPane();
              JTabbedPane tab = new JTabbedPane();
              tab.addTab("  Query  ", null, pane, "Query");
              tab.setMnemonicAt(0, KeyEvent.VK_1);
              return tab;
         private Box statusBar()
              Box sBar = Box.createHorizontalBox();
              JTextField linePosField = new JTextField(15);
              linePosField.setBackground(Color.LIGHT_GRAY);
              linePosField.setEditable(false);
              linePosField.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
              linePosField.setText(String.format("%s %d %s %d", "Line:",
                        getCaretRowPosition(pane), "Pos:",
                        getCaretColumnPosition(pane)));
              sBar.add(linePosField);
              return sBar;
          * Return the current line number at the Caret position.
         public int getCaretRowPosition(JTextPane textPane)
              int caretPosition = textPane.getCaretPosition();
              Element root = textPane.getDocument().getDefaultRootElement();
              return root.getElementIndex( caretPosition ) + 1;
          * Return the current Caret position.
         public int getCaretColumnPosition(JTextPane textPane)
              int offset = textPane.getCaretPosition();
              int column;
              try {
                   column = offset - Utilities.getRowStart(textPane, offset);
              } catch (BadLocationException e) {
                   column = -1;
              return column;
    }Edited by: G-Unit on Oct 17, 2010 4:08 AM

    Sorry, Found CaretListener(): Updated code;
    private JTabbedPane textPane()
       pane = new JTextPane();
       pane.addCaretListener(new CaretListener() {
          public void caretUpdate(CaretEvent e)
             linePosField.setText(String.format("%s %d %s %d", "Line:",
                getCaretRowPosition(pane), "Pos:",
                getCaretColumnPosition(pane)));
       JTabbedPane tab = new JTabbedPane();
       tab.addTab("  Query  ", null, pane, "Query");
       tab.setMnemonicAt(0, KeyEvent.VK_1);
       return tab;
    }Now I just have to figure out how to add a panel for line number to sit adjacent to my text area without throwing the whole window out of proportion. I tried adding some context menu buttons to sit next to it, and for some reason they seemed to want to grow by 500x the size specified and destroyed the whole look of the app. :s maybe I will just make do with status bar line numbers.
    Edited by: G-Unit on Oct 17, 2010 4:35 AM

  • 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

  • How can I get mouse pressed and mouse released positions on the desktop whi

    Hello All,
    I am generating a Frame using Swing API. My requirement is I need to capture the mouse pressed and mouse released positions, whenever user drags the mouse on desktop region (i.e. outside of the Frame). I require these points to find the rectangle region user has generated starting from mouse pressed to mouse released position. I need to pass that rectangle to Robot class in order to capture that desktop region.
    Can anybody help me out how can I achieve this using java on MAC, Linux and Windows platforms?
    Thanks in advance.
    Regards,
    VPKVL

    VPKVL wrote:
    DarrylBurke wrote:
    Can't be done in Java.I don't think that there is something which can't be done using java. When searched over net, found few applications which are using java for implementing this feature but not free, asking for license fee. I checked by downloading the demo version.
    Just want to know the hint how it can be achieved so that I can move further on that lines.
    Your thoughts ?They use JNI with the OS API.

  • How can I re-arrange the pages in a Pages document now?? I used to be able to click on the thumbnails and shift their position which is important in creating documents.  Any ideas?

    How can I re-arrange the pages in a Pages document now?? I used to be able to click on the thumbnails and shift their position which is important in creating documents.  Any ideas?

    This feature has been removed from Pages 5 along with over 90 others:
    http://www.freeforum101.com/iworktipsntrick/viewforum.php?f=22&mforum=iworktipsn trick
    Pages '09 is still in your Applications/iWork folder.
    Trash/archive Pages 5 and rate/review it in the App Store.
    Peter

  • 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

Maybe you are looking for