TextArea Insertion at current Caret Position

I am trying to figure out the best way to insert "text" in to
a textarea at the current caret position. Anyone have tips for
figuring out where to find this? In Flash you used to have
CaretIndex,
Im in the process of writing a code editor component, so
first off Im capturing the TAB key event, and then will insert an
actual TAB in the textarea... Right now I was just doing
this.Editor.text = this.Editor.text + ' '; But this is a stupid
stupid idea - so instead of appending it at the end, I need to
insert it in the current caret position.
Any tips would be greatly appreciated. Once I get it done, I
will be releasing it under either the Apache or GPL license.

Update: I have found
var text:String = this.Editor.text;
this.Editor.text =
text.substr(0,this.Editor.selectionEndIndex) + " " +
text.substr(this.Editor.selectionEndIndex);
this.Editor.setSelection(this.Editor.selectionBeginIndex+1,this.Editor.selectionBeginIndex +1);

Similar Messages

  • 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.

  • 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

  • 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

  • Javascript: set or get caret position in textarea -not in IE?

    Hi all
    another javascript question...
    I'm using a javascript function that gets the caret position
    (the cursor position) in the textarea,
    and stores it when the textarea gets out of focus, so that
    text can be inserted by clicking on a
    button, where the caret was previously in the textarea.
    I suppose many cms or html editors do that successfully
    somehow.
    But my function works in all browsers BUT IE.
    I remember giving up with the same problem years ago after I
    found documentation on how impossible
    or unreliable it was to make this work in IE.
    But I thought times had changed, and IE7 would improve on
    that matter.
    Apparently not?
    I found many that claim to work in all browsers, but the one
    I choose to use obviously does not...
    So do you guys know a script that does that and WORKS with
    IE?
    seb ( [email protected])
    http://webtrans1.com | high-end web
    design
    An Ingenious WebSite Builder:
    http://sitelander.com

    I'll link you something tonight - I wrote it like five years
    ago when I was in grade eleven. It's ugly code (as far as I can
    remember), but it has really advanced features and is REALLY easy
    to adapt to most situations.

  • Inserting text into a field at the current cursor position

    Does anyone know how to insert text into a field at the current cursor position? I would like it to work similar to the Syntax Palette in Forms. I cannot figure out how to retrieve the current cursor position in order to manipulate the text.
    Any help would be great.
    Thanks.

    Hi,
    If the button and the textfield are on in the same subform then this code should work in the click event of the button
    (This is JavaScript code so make sure the code is set to JavaScript and Client on the drop downs in the script window)
    (assuming the name of the textfield is TextField1)
    TextField1.rawValue = "some value";
    If they are in different subforms then you have 2 options
    Please note in both these options it is easier if the subforms have names ( I am assuming this to keep samples simple)
    option 1 -
    use the parent object to move up the tree till you are at the same level as that of the subform that contains the textfield
    e.g. 
    (Click Event of the button)
    this.parent.subformname.TextField1.rawValue = "some value";
    option 2 -
    Use the resolve node to make your way down from the top level of the form
    xfa.resolveNode ("form1.subformname.TextField1").rawValue = "some value";
    Hope this helps
    Malcolm
    p.s. I am making assumptions as the image/file you attached did not appear for me.

  • RichTextEditor - insert character at current cursor position?

    I've been looking everywhere but I can't find a way to insert
    a character in a RichTextEditrs current cursor position. I'm trying
    to create a soft keyboard for spanish special letters and symbols
    for an application.

    There is a property
    selection of the RichTextEditor control. This is a reference
    to a TextRange, which is the current selection or if nothing is
    selected, it's a TextRange of 0 length at the current position of
    the cursor.
    All you need to do to insert a character at the current
    position is:
    your rich text editor].selection.htmlText = "Insert text";

  • TextArea insert problem

    Hi I am reading a file and adding it to a text area. I then want to move the cursor to a position in the textarea, and click a button to add text. The text I want to add should be at the current cursor position, I have tried to set i = tArea1.getCaretPosition, then use tArea1.insert("Blah Blah Blah", i), but the text gets added at the end of the current data
    Help........
    KPJ

    works fine for me here.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.BevelBorder;
    public class Test extends JFrame{
         DataField inputField, outputField;
         Container cont;
         public Test() {
              this.setBackground(Color.black);
              this.setSize(500,500);
              inputField = new DataField("enter a word or phrase", true);
              outputField=new DataField("below are the results", true);
              inputField.tf.addKeyListener(new KeyAdapter(){
                       public void keyPressed(KeyEvent e){
                            if (e.getKeyCode()==KeyEvent.VK_ENTER){
                                 e.consume();
                                 outputField.tf.insert(inputField.tf.getText(),outputField.tf.getCaretPosition()); //tf is the TextArea in the DataField
                                                                 //this is where text is inserted.
              cont=this.getContentPane();
              cont.setLayout(new BorderLayout());
              cont.add(inputField, "North");
              cont.add(outputField, "Center");
              this.setVisible(true);
         public static void main(String[] args){
              new Test();
    class DataField extends JPanel{
         JTextArea tf;
         JLabel label;
         public DataField(String string, boolean editable){
              super();
              label=new JLabel(string);
              label.setOpaque(true);
              label.setForeground(Color.lightGray);
              label.setBackground(Color.blue);
              tf=new JTextArea();
              tf.setBackground(Color.white);
              tf.setForeground(Color.black);
              tf.setEditable(editable);
              this.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.blue, Color.blue) );
              this.setBackground(Color.white);
              this.setLayout(new BorderLayout());
              this.add(label,"North");
              this.add(tf,"Center");
         public String get(){
              return tf.getText();
         public void set(String string){
              tf.setText(string);
    }

  • Keeping track of caret position when using scrollbars

    Hi!
    I have a jtextarea contained in a jscrollpane, To the jtextarea I have added a caretlistener. The textarea displays a lot of log output that will not be editable. When I move the cursor in the textarea I get updates of the caret position. The problem is that when I use the scrollbars the caret position does not move, which might be the right way. But I would like just that, that is to get an update on which line or position that I am currently on.
    The problem is that the log output is very large so I have to keep track on where I am in the log file, and only have a portion of the log information from the file in the textarea.
    Some pointers, suggestions or examples would really be appreciated.
    Best regards
    Lars

    yes....
    you can do using context listeners....
    in the start of context listeners read from the file and add to context ... and when the context becomes inactive write to a file....
    for that you should use tomcat4.01 ... cause only tat has servlet 2.3 implementaion.
    if you are not using tat .. write to the file every 10 minutes .. atleast you will have the latest update of the counts when something crashes......................

  • How to get the current cursor position in word report?

    I am generating a word report. But I would like to keep the table in one page. However, I did not find the way to do it in labview. Somebody would give me some suggestions? I appreciate a lot.
    One way I think I can do is to find the current cursor position. Since I know the table size so I can figure out if the left space in the current page is enough to hold the table. But I do not know how to locate the curent cursor position in word document in labview programmatically. I appreciate any suggestions on this question.
    Thanks.

    Hi,
    when you insert data in a word document you have to refer to bookmarks rather than cursor position.
    If you are using the Report Generation Toolkit for Office it is explained in the manual chapter 3-1.
    See also the example: Generate Report From Template (Word).vi included in the toolkit.
    If you aren't using the toolkit, you still have to refer to bookmark as reference points to insert and/or fetch data.
    The principle is:
    - First create a document in which you insert bookmarks where you wish and save it as a template
    - In LV open your template document and insert in it your data referring to bookmarks as insertion points
    - At the end save your report with another name, so you still have the template
    I hope I have been clear enough, if not just as
    k!
    Good luck,
    Alberto

  • 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

  • Is caret positioning in right-to-left oriented jtextpane corruptable?

    Dear all -
    Below is a serious problem. I hope I can get help from you experts out there; otherwise, I think it is a bug that should be reported to the JDK developers.
    I am writing an editor using my own keyboard layout to type in Arabic. To do so, I use jTextPane, and my own implementation of DocumentFilter (where I map English keys to Arabic letters). I start by i) setting the component orientation of jTextPane to be from RIGHT_TO_LEFT, and ii) attaching a caretListener to trace the caret's position.
    The problem (I think it is a bug just like what is recorded here: http://bugs.adobe.com/jira/browse/SDK-16315):
    Initially as I type text in Arabic, there is one-to-one correspondence between where I point my mouse and where the caret displays, basically, the same place. However, a problem occurs (and can always be re-produced) when I type a word towards the end of the line, follow it by a space character, and that space character causes the word to descend to the next line as a result of a wrap-around. Now, as I point my mouse to that first line again, the location where I click the mouse and the location where the caret flashes are no longer coincident! Also, the caret progression counter is reversed! That is, if there are 5 characters on Line 1, then whereas initially the caret starts from Position 0 on the right-hand side and increases as more text is added from right to left, it is now reversed where the the caret now increases from left to right for the first line, but correctly increases from right to left in the second line! yes funny stuff and very hard to describe to.
    So, here is an example. I wrote the code below (JDK1.6_u10, on Netbeans 6.5 RC2) to make it easy to reproduce the problem. In the example, I have replaced the keys A, S, D, F and G with their Arabic corresponding letters alif, seen, daal, faa and jeem. Now, type these letters inside the double quotes (without the double quotes) including the two spaces please and watch out for the output: "asdfg asdfg ". Up until you type the last g and before you type space, all is perfect, and you should notice that the caret position correctly moves from 0 upwards in the printlines I provided. When you type that last space, the second word descends as a result of the wrap-around, and hell breaks loose! Notice that whereas the mouse and caret position are coincident on the second line, there is no way to fine-control the mouse position on the first line any more. Further, whereas adding text on the second line is intuitive (i.e., you can insert more text wherever you point your mouse, which is also where the caret would show up), for the first line, if you point the mouse any place over the written string, the caret displays in a different place, the any added text is added in the wrong place! All this because the caret counter is now reversed, which should never occur. Any ideas or fixes?
    Thank you very much for reading.
    Mohsen
    package workshop.onframes;
    import java.awt.ComponentOrientation;
    import java.awt.Rectangle;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    public class NewJFrame1 extends javax.swing.JFrame {
    public NewJFrame1() {
    initComponents();
    jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    CaretListener caretListener = new CaretListener() {
    public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot == mark) {
    try {
    Rectangle cc = jTextPane1.modelToView(dot);
    System.out.println("Caret text position: " + dot +
    ", view location (x, y): (" + cc.x + ", " + cc.y + ")");
    } catch (BadLocationException ble) {
    System.err.println("CTP: " + dot);
    } else if (dot < mark) {
    System.out.println("Selection from " + dot + " to " + mark);
    } else {
    System.out.println("Selection from " + mark + " to " + dot);
    jTextPane1.addCaretListener(caretListener);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane3 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jTextPane1.setAutoscrolls(false);
    jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextPane1KeyTyped(evt);
    jScrollPane3.setViewportView(jTextPane1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jTextPane1KeyTyped(java.awt.event.KeyEvent evt) {
    if (evt.getKeyChar() == 'a') {
    evt.setKeyChar('\u0627');
    } else if (evt.getKeyChar() == 's') {
    evt.setKeyChar('\u0633');
    } else if (evt.getKeyChar() == 'd') {
    evt.setKeyChar('\u062f');
    } else if (evt.getKeyChar() == 'f') {
    evt.setKeyChar('\u0641');
    } else if (evt.getKeyChar() == 'g') {
    evt.setKeyChar('\u062c');
    public
    static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame1().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
    }

    Hi Mohsen,
    I looked at it and indeed, I see what you describe. Sorry, but I can't shed any light. I tried to figure out what software component, or combination of components, is the cause of the problem. I see several candidates:
    1) The JTextPane
    2) The Document
    3) RTL support
    4) BIDI support
    5) Interpretation (by any other software component) of the left and right arrow key
    6) The font
    To clarify number 6: I know virtually nothing of Arabic language (apart from it being written from right to left). I remember however that the actual representation of a letter is dependent of its position between other letters: front, middle and end. What I see to my astonishment is that it seems that the rendering is also aware of this phenomenon. When you insert an A between the S and D of ASDFG, the shape of the S changes. Quite magic.
    I tried to add a second textpane with the same Document, but a different size, to see what would happen with number one if one types text in number two and vice versa.
    In my first attempt, the font that you set on textpane one was gone after I set its document to number two. For me that is very strange. The font was set to the textpane, not to the document. The separation betweem Model and View seems not very clear in this case. So I now also set that font on the second textpane.
    I will post the changed code so that you may experiment some more and hopefully will find the problem.
    You might be interested in a thread on java dot net forums that discusses a memory leak for RTL [http://forums.java.net/jive/message.jspa?messageID=300344#300344]
    Piet
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class NewJFrame1 extends JFrame {
        private static final long serialVersionUID = 1L;
        public NewJFrame1() {
         initComponents();
         // jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         this.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         CaretListener caretListener = new CaretListener() {
             public void caretUpdate(CaretEvent e) {
              int dot = e.getDot();
              int mark = e.getMark();
              if (dot == mark) {
                  try {
                   Rectangle cc = jTextPane1.modelToView(dot);
                   System.out.println("Caret text position: " + dot
                        + ", view location (x, y): (" + cc.x + ", "
                        + cc.y + ")");
                  } catch (BadLocationException ble) {
                   System.err.println("CTP: " + dot);
              } else if (dot < mark) {
                  System.out.println("Selection from " + dot + " to " + mark);
              } else {
                  System.out.println("Selection from " + mark + " to " + dot);
         jTextPane1.addCaretListener(caretListener);
        private KeyAdapter toArabic = new KeyAdapter() {
         public void keyTyped(KeyEvent evt) {
             jTextPane1KeyTyped(evt);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        // @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
         jScrollPane3 = new JScrollPane();
         jTextPane1 = new JTextPane();
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         jTextPane1.setFont(new Font("Tahoma", 0, 24)); // NOI18N
         jTextPane1.setAutoscrolls(false);
         jTextPane1.addKeyListener(toArabic);
         jScrollPane3.setViewportView(jTextPane1);
         GroupLayout layout = new GroupLayout(getContentPane());
         getContentPane().setLayout(layout);
         layout.setHorizontalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.DEFAULT_SIZE, 159,
                   Short.MAX_VALUE).addContainerGap()));
         layout.setVerticalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.PREFERRED_SIZE, 85,
                   GroupLayout.PREFERRED_SIZE).addContainerGap(
                   GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
         pack();
        }// </editor-fold>
        private void jTextPane1KeyTyped(KeyEvent evt) {
         if (evt.getKeyChar() == 'a') {
             evt.setKeyChar('\u0627');
         } else if (evt.getKeyChar() == 's') {
             evt.setKeyChar('\u0633');
         } else if (evt.getKeyChar() == 'd') {
             evt.setKeyChar('\u062f');
         } else if (evt.getKeyChar() == 'f') {
             evt.setKeyChar('\u0641');
         } else if (evt.getKeyChar() == 'g') {
             evt.setKeyChar('\u062c');
        public static void main(String args[]) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
              final NewJFrame1 frameOne = new NewJFrame1();
              frameOne.setLocationRelativeTo(null);
              frameOne.setVisible(true);
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                   Document doc = frameOne.jTextPane1.getDocument();
                   JTextPane textPane2 = new JTextPane();
                   textPane2.setFont(new Font("Tahoma", 0, 24)); // NOI18N
                   textPane2.setAutoscrolls(false);
                   textPane2.setDocument(doc);
                   textPane2.addKeyListener(frameOne.toArabic);
                   JFrame frameTwo = new JFrame();
                   frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frameTwo.add(new JScrollPane(textPane2));
                   frameTwo.setSize(400, 300);
                   frameTwo.setLocationByPlatform(true);
                   frameTwo.setVisible(true);
                   frameTwo
                        .applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        // Variables declaration - do not modify
        private JScrollPane jScrollPane3;
        private JTextPane jTextPane1;
        // End of variables declaration
    }

  • Find attributes of HTMLDocument at caret position

    Can anyone tell me how I can find all the attributes of the HTML document I am working on at the current caretposition? I need to be able to tell if the text at the caret positon is bold, part of a list, linked and so on.

    Hi,
    the answer to your question is twofold. Bold is stored in an HTMLDocument as an attribute. The other items you mention (part of a list, links) are elements by themselves.
    To find out, whether or not text at the caret position is bold can be done by (assuming, your document is shown in a JEditorPane)
    HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
    Object attr = doc.getCharacterElement(editorPane.getSelectionStart()).getAttributes().getAttribute(CSS.Attribute.FONT_WEIGHT);But if the text portion in question is bold because of a setting within an associated style sheet, additional coding would be necessary (getting the style sheet, getting the attributes for the style class, etc.). As well, an attribute could come from a setting within the paragraph instead of the actual text portion referring to (again additional coding).
    To find out if text at the caret position is part of a list or a link, you have to inspect the surrounding elements basically by using getCharacterElement and then iterating up in the element tree with getParentElement().
    I recommend to read the related API docs in javax.swing.text and javax.swing.text.html
    Ulrich

  • ComboBox caret position

    I am developing a form with ComboBox as a subject (the user can choose one from the list , or type one)
    and TextArea where the user can write his notes (attached a picture)
    The user using a virtual keyboard (touch) to enter any characters.
    (I am using the append method to append the next Char to the TextInputControl class (both Combo and TextArea Inherit from it
    When I try to deletePreviousChar() in the TextArea it works, but in ComboBox it fails
    I put some System.out.println() (I am an old fashion guy) to see what is the problem and it seems that with the ComboBox the class is loosing the Caret position after every action
    Here is my code: (Look it also as a attached picture)
    public void changed(ObservableValue<? extends String> observable,
      String oldVal, String newVal) {
      if (newVal != null) {
      if (lastNodeInFocus instanceof TextArea) {
      switch (newVal) {
      case Keyboard.KEY_CODE_DLT_PREV_CHAR:
      System.out.println("TA - dlt  :" + notes.getCaretPosition());
      notes.deletePreviousChar();
      break;
      default:
      System.out.println("TA - Append B  :" + notes.getCaretPosition());
      notes.appendText(newVal);
      System.out.println("TA - Append A  :" + notes.getCaretPosition());
      break;
      }else{
      switch (newVal) {
      case Keyboard.KEY_CODE_DLT_PREV_CHAR:
      System.out.println("CB - dlt  :" + topTenSubjects.editorProperty().getValue().getCaretPosition());
      System.out.println(topTenSubjects.editorProperty().getValue().deletePreviousChar());
      break;
      default:
      System.out.println("CB - append B :" + topTenSubjects.editorProperty().getValue().getCaretPosition());
      topTenSubjects.editorProperty().getValue().appendText(newVal);
      System.out.println("CB - append A :" + topTenSubjects.editorProperty().getValue().getCaretPosition());
      break;
      keyboard.keyPressed.set(null);
    Here is the Debug results:  CB = Combo  TA = TextArea  B=Before  A=After , the numbers are the caret position (also attached as a picture )
    CB - append B 0
    CB - append A :1
    CB - append B 0
    CB - append A :2
    CB - append B 0
    CB - append A :3
    CB - append B 0
    CB - append A :4
    CB - dlt  0
    false
    CB - dlt  0
    false
    TA - Append B  0
    TA - Append A  :1
    TA - Append B  :1
    TA - Append A  :2
    TA - Append B  :2
    TA - Append A  :3
    TA - Append B  :3
    TA - Append A  :4
    TA - dlt  :4
    TA - dlt  :3
    TA - dlt  :2
    TA - dlt  :1
    Maybe it is a Bug?
    Shlomo

    Hi all
    I opened at JIRA  an issue RT-40120
    It will be reviewed by Oracle team and will be resolved at version 9
    Shlomo

  • 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

  • N200 can not view additional music on dev

    I have been searching this site for hours attempting to find a solution;?I can see the music in the MUVO N200 desktop programs...WMP 0 and other programs however, I can see the music files in the device. Files are saved in .wma? I have the latest fir

  • Re: Why can't I have a raincheck when the ad does not say limited quantities?

    Not the same person, but is it possible to get a rain check for this deal whether it is online or in store? The games I wanted to buy are out in both options.

  • Java.lang.NullPointerException in 8.1 with soap doc literal binding

    hi, scenario: 1) web service with soap doc literal binding on external server. web service is expecting a complex input argument 2) generate web service control in weblogic 8.1 (sp1) workshop 3) wrote jws file to use the web service control 4) run te

  • SRKIM: R12: GL_INTERFACE IN R12

    PURPOSE R12 에서 GL_INTERFACE TABLE 의 쓰임에 대해 알아 보도록 한다. SOLUTION R12 에서는 R11i 때와는 달리 subledger module 에서gl transfer 를 수행 한다고 해서 데이타가 무조건 GL_INTERFACE TABLE 로 가지 않는다. profile option 'SLA: Disable Journal Import = No' 이 설정 되어 있는 경우 AP 등의 SUBLEDGER 에서 GL

  • ISync unable to launch: iSync manager is unavailable

    Hi guys, I recently took my computer in to an authorised repairer (MyMac Flinders St., Melbourne Australia) to get my LCD screen replaced under warranty, as it had developed a yellow line running down the right hand side of the screen. Whilst it was