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

Similar Messages

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

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

  • Problem in setting desired position for JPanel in JScrollPane!!!

    Dear Friends,
    I am having problem to set desired Scrollable(JScrollPane) JPanel position. I have a JPanel in a JFrame which is scrolable with lot of objects. It automatically displays on the top position inside JScrollPane, I want to set scroll position on the middle for the panel.
    I went through the search for the same in this forum, i found some posts related to this but they are linked with JTextArea(setCaretPosition). With JPanel i can't set caret position.
    Could anyone guide me how to set the scroll position on middle.
    Regards..
    Jayshree

    Replace:
    if(view.getValueAt(row,column) instanceof ImageIcon){
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
          }with:
    if(view.getValueAt(row,column) instanceof ImageIcon)
            view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
           view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

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

  • Set a popup Dialog to just below the caret position in TextField

    I have a JTextArea in which I wish to show up a popup dialog box whenever the user presses Ctrl and I want the popup to be visible just below the caret position where the user presses Ctrl. I'm using modelToView() but I'm not able to achieve the target.
    If anyone can help...

    You may find this usefull (if you have not already)
    http://www.java2s.com/Code/JavaAPI/javax.swing/JTextFieldmodelToViewintpos.htm
    If you have seen that and it still doesn't work we need an example to work with (as the above poster says) as you havn't even really explained what is going wrong!

  • 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

  • Dynamically Setting the Position of a Subform

    Hello there
    I am trying to solve an issue with the dynamic positioning of a subform not working when the form is rendered from a process.
    I have a flowed XDP based form with a variable amount of content, and a “totals” subform that needs to be positioned at the bottom of the last page.  I do this with some JavaScript which works out the current Y position of the “totals” subform, and then sets the top margin of a proceeding “spacer” subform appropriately.  The code runs on the docReady eavent of the main subform, and runs correctly when the form is rendered dynamically, for example from within Designer.
    We need to be able to generate the form using a LiveCycle service.   When we attempt this using the generatePDFOutput service, the code correctly calculates and sets the required margin.  However, setting the margin has no effect (the “totals” subform is not moved).  I am unclear why this does work, i.e. why there is a different effect when rendering the form from the process.
    I am unable to move the code to an earlier event.  The latest event for which setting a margin actually works is formReady.  However, at this point the code to determine the current Y position of the “Totals” subform does not work.
    One idea I had was to render the form twice.  On the first rendering of the form, the code could calculated the required margin.  On the 2nd rendering of the form, the margin would be set at an appropriately early event such as initialise.  However, I do not know how to pass a value calculated in JavaScript back to a process.
    Any ideas would be appreciated.
    Many thanks
    Geoff Olding

    Hi,
    You can set the caret position in the JTextPane with the method(in JTextComponent) :
    public void setCaretPosition(int position)For exemple :
    myJTextPane pane = ...
    Document doc = myJtextPane.getStyledDocument();
    if(doc!=null){
      myJTextPane.setCaretPosition(doc.getLength());
    }bye

  • 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

  • Caret Position always remain unchanged

    Hi,
    I've tried inserting some strings and components into a JTextPane, but the caret position always remain at 0 irregardless. Is this the expected behavior?
    My expected behavior is that the caret is to at the end of the document, after each insertion of strings or components. Therefore i'll need to explicitly set the caret position to EOF after each insertion. Is there another approach to this issue?
    =========================================
    StyledDocument doc = textPane.getStyledDocument();
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition is 0
    textPane.insertComponent( new JButton("temp"));
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition still remain as 0
    doc.insertString(doc.getLength(), message, null);
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition still remain as 0
    ==============================================

    Please use code tags like so on this forum:
    StyledDocument doc = textPane.getStyledDocument();
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition is 0
    textPane.insertComponent( new JButton("temp"));
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition still remain as 0
    doc.insertString(doc.getLength(), message, null);
    System.out.println( "" + textPane.getCaretPosition());
    // value of caretposition still remain as 0{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • JcomboBox caret position

    I want to create a jcombobox that accepts only dates... But I have no idea how to capture the caret position.....
    There doesn't seem to be another default method to know where the caret position.
    Any help?
    Thanks,
    V

    Well first of all to even have a caret in your combo box you need to make sure you have it set as editable.
    This is a good tutorial to show you how...
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#editable
    Using the example ComboBoxDemo2.java from that tutorial I was able to add a few lines of code to get the caret position. Since the JComboBox class does not implement the getCaretPosition() you can use the method getEditor() to return the ComboBoxEditor. Then use the ComboBoxEditor's method getEditorComponent and cast it to a JTextField. Now you can use the JTextField's method getCaretPosition() to return the caret position.
    Does that make sense? I was able to get it to work that way.
    Good luck,
    .kim

  • How to set the position in SAP Script

    Hi Professionals,
    Can anyone tell me that How can I set the position of an bitmap Image (after inserting) in SAP Script ?
    by default position is in Left, I need to align it in center or somewhere else.
    Anybody knows, kindly reply!
    Thanks
    Devinder

    Hi,
    But Can we assign a window under another window. Because I want to insert a bmp picture on particular position.
    example:- there is a digital signature and wanted to insert upon a name.
    So, there is a text (which is customer name) and digital signature (in bmp picture format) upon it.
    Thanks
    Devinder

  • 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

  • I need to set the position of components on a page that contains a MenuBar,

    I need to set the position of components on a page that contains a MenuBar, but MenuBar does not provide a getPreferred size method.
    How can I get the MenuBar's size in AWT?
    Thanks.

    A menubar is not a general component that is added to a frame like any another. It is the specific responsibility of the setMenuBar/setJMenuBar methods to deal with this.

Maybe you are looking for

  • Just a question to make sure this is normal.

    Hi all, I installed Leopard on my MBP, went smooth, no problems. Now...my question is, in Tiger, when you start up you see the grey screen with the apple and gear, then you see a blue screen with the Mac OSX box and the blue bar. In Leopard, when I s

  • CO01 - automatic release

    Hello, When I create a new PO with CO01, I have to release manually each PO with CTRL-F1. I know there is a way to perform an automatic release during the creation of the PO (it worked on our previous system). Could you please let me know how I can f

  • IMac 24'

    i'm thinking about getting an iMac 24' with 2.8GHz intel core 2 extreme, 2GB memory, 500GB 72rpm hard drive. My question is since i use a lot of soft synths in my recordings will this machine handle it well enough? Does anyone use the IMac 24' with l

  • Copy and Paste text into AEFX stopped working

    I have succeeded in copying and pasting two paragraphs of text from Word Pad into AEFX. (ie two layers). I applied Typewriter FX and adjusted parameters , exported etc all fine. Took a break and now I can not seem to get the Copy and Paste to work an

  • Problem to display a checkbox in PDF generated by XML Publisher

    Hi All, i need your help, i have create and PDF template with checkbox field. when i generate the report from Oracle Application using XML Publisher all is fine only the filed checkbox which is inactive, i can't do any check/Uncheck in the filed. Tha