Moving caret in a textfield

I have several textfields with default values displayed ... but the insertion point always end up at the beginning and it is annoying to change the values that way (much easier to have it at the end to use the backspace).
I see how to get the caret position, bu can't figure out how to set it. How do I move the insertion point to the end by default?

No really the answer I was hoping for,
but I guess it is an answer. Thanks.Actually I was watching your topic hoping someone would come up with some way to do it -- I have an app with numerical data where the last 1 or 2 digits change frequently, and this would have been useful to me too.
When there were no responses for 2 days I spent some time searching and could not find any practical way to do it.
If you happen to find a way, please do post it here :-)
db

Similar Messages

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

  • Moving caret to a specific line number

    I'm working on a text editor and I've been struggling with the goto function. I've tried several different things and I'm close. I can calculate the correct x and y coordinates to send the caret to, but I can't make it move. Here is what I have now:
    if (line > jta.getLineCount()) {
         line = jta.getLineCount();
    DefaultCaret dc = (DefaultCaret) jta.getCaret();
    Point spot = new Point(0, (line - 1)*jta.getRowPixels());
    System.out.println(spot);
    dc.setMagicCaretPosition(spot);
    System.out.println(dc.getMagicCaretPosition());
    dc.setLocation(spot);//this doesn't work, and neither does setting jta's caret to dc

    Check out the gotoLine(...) method:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607777&start=4

  • Moving object (like button, textfield ,label,.....)

    if I have an object in the applet area like (button , textfield, label,....) and if I want to move the object buy simply click on the object and drag it to move it.
    if someone a solution send to me on :
    "[email protected]"

    if I have an object in the applet area like (button ,
    textfield, label,....) and if I want to move the
    object buy simply click on the object and drag it to
    move it.
    if someone have a solution send it to me on :
    "[email protected]"

  • Moving cursor to another TextField & Max. Frame.

    Hi All.
    I have 2 questions reffer to the following code.
    1. How to move cursor from tffirstname to tflastname, tfaddress and tfphone
    with use Enter key press on the keyboard?
    2. At the first run time i want the form size automatically have a Maximum
    Window, how to do it?
    Thank a lot.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DataInput01
         JFrame frm = new JFrame("Input Personal Data");
         Container pane;
         JLabel     lbfirstname,
                   lblastname,
                   lbaddress,
                   lbphone;
         JTextField      tffirstname,
                        tflastname,
                        tfaddress,
                        tfphone;
         JButton btok,
                   btcancel;
         public DataInput01()
              lbfirstname = new JLabel("First Name :");
              lblastname = new JLabel("Last Name :");
              lbaddress = new JLabel("Address :");
              lbphone = new JLabel("Phone :");
              tffirstname = new JTextField(15);
              tflastname = new JTextField(15);
              tfaddress = new JTextField(15);
              tfphone = new JTextField(15);
              btok = new JButton("Submit");
              btcancel = new JButton("Go Home");
              pane = frm.getContentPane();
              pane.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
              pane.add(lbfirstname);
              pane.add(tffirstname);
              pane.add(lblastname);
              pane.add(tflastname);
              pane.add(lbaddress);
              pane.add(tfaddress);
              pane.add(lbphone);
              pane.add(tfphone);
              pane.add(btok);
              pane.add(btcancel);
              frm.setBounds(0, 0, 280, 200);
              frm.setResizable(false);
              frm.setContentPane(pane);
              frm.setVisible(true);
              frm.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              btcancel.addActionListener(new ActionListener()
              { public void actionPerformed(ActionEvent e)
         { System.exit(0);}
         public static void main(String args[])
              new DataInput01();
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class DataInput01
    JFrame frm = new JFrame("Input Personal Data");
    Container pane;
    JLabel lbfirstname,
    lblastname,
    lbaddress,
    lbphone;
    JTextField tffirstname,
    tflastname,
    tfaddress,
    tfphone;
    JButton btok,
    btcancel;
    public DataInput01()
    lbfirstname = new JLabel("First Name :");
    lblastname = new JLabel("Last Name :");
    lbaddress = new JLabel("Address :");
    lbphone = new JLabel("Phone :");
    tffirstname = new JTextField(15);
    tflastname = new JTextField(15);
    tfaddress = new JTextField(15);
    tfphone = new JTextField(15);
    btok = new JButton("Submit");
    btcancel = new JButton("Go Home");
    pane = frm.getContentPane();
    pane.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
    pane.add(lbfirstname);
    pane.add(tffirstname);
    pane.add(lblastname);
    pane.add(tflastname);
    pane.add(lbaddress);
    pane.add(tfaddress);
    pane.add(lbphone);
    pane.add(tfphone);
    pane.add(btok);
    pane.add(btcancel);
    //changes
    java.util.Set forwardKeys = new java.util.HashSet();
    forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
    forwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0));
    pane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,forwardKeys);
    //frm.setBounds(0, 0, 280, 200);
    frm.setExtendedState(JFrame.MAXIMIZED_BOTH);
    //frm.setResizable(false);
    //end changes
    frm.setContentPane(pane);
    frm.setVisible(true);
    frm.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    btcancel.addActionListener(new ActionListener()
    { public void actionPerformed(ActionEvent e)
    { System.exit(0);}
    public static void main(String args[])
    new DataInput01();
    }

  • Caret not painted in JTextPane

    Hi!
    If I insert a JTextField in JTextPane and set the caret at the position of the JTextField, the Caret is not visible. It seems it is behind the JTextField. Can anybody help me what I could do so that the caret is always visible for the user so that he/she can always know the position of the caret.
    Thanks!
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(Font f, String text,
                   StyledDocument doc) {
              MutableAttributeSet a = new SimpleAttributeSet();
              StyleConstants.setFontSize(a, f.getSize());
              StyleConstants.setFontFamily(a, f.getFamily());
              try {
                   doc.insertString(doc.getLength(), text, a);
              catch (BadLocationException x) {
         private void insertTextFieldInTextPane(Font f, String text,
                   JTextPane tp, int pos) {
              JTextField tf = new JTextField(text, text.length()) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tf.setFont(f);
              FontMetrics fm = tf.getFontMetrics(f);
              int maxAscent = fm.getMaxAscent();
             int height = (int)tf.getPreferredSize().getHeight();
              int borderHeight = tf.getBorder().getBorderInsets(tf).top;
              int aboveBaseline = maxAscent + borderHeight;
              // if you comment the next line out you can see a part of the caret
              float alignmentY = (float)(aboveBaseline)/((float)(height));
              tf.setAlignmentY(alignmentY);
              tp.setCaretPosition(pos);
              tp.insertComponent(tf);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              Font f = new Font("SansSerif", Font.PLAIN, 24);
              this.insertStringInTextPane(f, "* ", doc);
              this.insertTextFieldInTextPane(f, "********", tp, doc.getLength());
              this.insertStringInTextPane(f, " ********", doc);
              tp.setEditable(true);
              tp.setCaretPosition(2);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocationByPlatform(true);
              this.setSize(400,400);
              this.setVisible(true);
         public static void main(String[] args) {
              new TextPaneTest2();
    }

    camickr, thanks for your answer. I polished your solution with LineBorder and setOpaque by using a CompoundBorder:
    tf.setBorder( new CompoundBorder(new LineBorder(new Color(0, 0, 0, 0), 2), tf.getBorder()));In this case the original Look&Feel of JTextField is honoured and the Caret is clearly before the JTextField and not on the border. If it is painted on the border the user might have some problems to recognize if the caret is before textField or in textfield.
    Thank you very much!
    Message was edited by:
    the12hunters

  • JTextPane and caret

    Hi,
    does anyone know if I can get an intention of moving caret before it actually moves? If I add caret listener, I get the event but the caret has been already moved, so it does not satisfy me.
    Regards

    camickr wrote:
    What is your problem and what is your requirement. If we know this maybe we can suggest an alternative solution.Exactly. There's no direct support for what you want to do, but there could very well be an alternative solution.
    Otherwise I would suggest that you need to write a custom Action for the arrow keys to replace the existing Action.True, but changing the actions for the arrow keys won't handle mouse input (i.e. if the user uses the mouse to make a selection).
    Off the top, I'd say you could subclass DefaultCaret, and override setDot() and moveDot() so they fire a special event you create and define. In order for that to work though, you'd have to do some testing and make sure that one of those two methods is the only way the caret ever changes location (i.e., there isn't some internal, private method in DefaultCaret that bypasses setDot() and moveDot()).

  • Update 10 rendering problem

    After updating to java 6 update 10 i suddenly experience a weird rendering problem. Before updating all my borders where crisp but now they're blurry and ugly. Also the caret in the textfield is blurry. See example here
    It looks like some antialiasing setting ore something.
    How can I solve this problem?
    Edited by: slum_x on 20-10-2008 16:33

    My video card driver is set to "Application controlled" and I also have the newest set of drivers so that doesn't seem to be the problem. But still it looks like an antialias problem. Anyone found a solution?
    /peter

  • How to insert a String at the CaretPosition without moving the Caret?

    I have a JTextPane wrapped by a JScrollPane. The JTextPane is where chatroom messages appear. When a message is appended at the end, it determines whether to scroll to the bottom based on some conditions (scroll to the bottom only if the user was already viewing somewhere near the bottom). That part is working fine.
    Although the JTextPane is not editable, it allows the user to make selections using a mouse so that blocks of text can be copied from the chatroom. The default caret of JTextPane handles that for me.
    But the problem comes when the caret position is at the end of the document when my program inserts a new message with the following code:
    StyledDocument doc = textPane.getStyledDocument();
    doc.insertString(doc.getLength(), message + "\n", null);The caret was at doc.getLength() to begin with, when the new message is inserted at the end, it "pushes" the caret to a new position. The caret movement is causing JScrollPane to scroll to where the caret is visible (the bottom), therefore interfering with my scrolling algorithm (see above).
    So, when the caret is doc.getLength(), how do I insert a String at doc.getLength() with the caret staying at the original position?
    In other words, how do I insert a String at the caret position without the caret being moved?
    Note:
    1) I don't want to use setCaretPosition() to set the caret to its original position, because calling this method will trigger a CaretEvent, thus causing the JScrollPane to scroll (to the caret) which is not what I want (see above).
    2) I don't want to remove the CaretListener, cause then the JScrollPane won't scroll even when the user wants to make a multiple-page selection using the mouse (dragging the selection off screen).
    3) I want to keep the Caret at the original position so that the user won't lose his/her selection when new messages appear (which can be quite frequent).

    I keep forgetting how difficult it is to do such simple things in the text package. But it's not impossible! Here's a way to replace the relevant listeners, plus a sample implementation. If you know you'll never, ever delete any text from the JTextPane, you may not have to provide a replacement DocumentListener at all; this one just makes sure the caret isn't past the end of the document.
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.text.DefaultCaret;
    import javax.swing.text.Document;
    import javax.swing.text.JTextComponent;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    public class ChatCaret extends DefaultCaret
      private MyHandler newHandler;
      private PropertyChangeListener oldHandler;
      public void install(JTextComponent c)
        super.install(c);
        PropertyChangeListener[] pcls = c.getPropertyChangeListeners();
        for (int i = 0; i < pcls.length; i++)
          if (pcls.getClass().getName().equals(
    "javax.swing.text.DefaultCaret$Handler"))
    oldHandler = pcls[i];
    newHandler = new MyHandler(oldHandler);
    c.removePropertyChangeListener(oldHandler);
    c.addPropertyChangeListener(newHandler);
    break;
    Document doc = c.getDocument();
    if (doc != null)
    doc.removeDocumentListener((DocumentListener)oldHandler);
    doc.addDocumentListener(newHandler);
    public void deinstall(JTextComponent c)
    super.deinstall(c);
    c.removePropertyChangeListener(newHandler);
    Document doc = c.getDocument();
    if (doc != null)
    doc.removeDocumentListener(newHandler);
    class MyHandler implements PropertyChangeListener, DocumentListener
    private PropertyChangeListener oldHandler;
    MyHandler(PropertyChangeListener oldHandler)
    this.oldHandler = oldHandler;
    public void propertyChange(PropertyChangeEvent evt)
    Object oldValue = evt.getOldValue();
    Object newValue = evt.getNewValue();
    if ((oldValue instanceof Document) ||
    (newValue instanceof Document))
    setDot(0);
    if (oldValue != null)
    ((Document)oldValue).removeDocumentListener(this);
    if (newValue != null)
    ((Document)newValue).addDocumentListener(this);
    else
    oldHandler.propertyChange(evt);
    public void removeUpdate(DocumentEvent evt)
    int length = getComponent().getDocument().getLength();
    if (length < getDot())
    setDot(length);
    public void insertUpdate(DocumentEvent evt) { }
    public void changedUpdate(DocumentEvent evt) { }

  • Moving the caret in a non-editable JTextPane ??

    Hi,
    I would like to know if it's possible to have a visible and moveable caret (with the directional arrows) in a JTextPane which has to be non editable.
    If you know how to do, could you please answer and give the solution
    Thanks in advance

    Every text component has its own caret. It would look ugly to have the caret flashing for every text component on the screen, so when a text component loses focus the the caret is hidden - setVisible(false).
    When an editable text component regains focus the caret is set visible automatically. For uneditable text components you have to set the caret visible yourself.
    textPane.addFocusListener( new FocusAdapter()
         public void focusGained(FocusEvent e)
              JTextComponent component = (JTextComponent)e.getSource();
              component.getCaret().setVisible(true);
    });

  • Moving a TextField in Swing.Possible?please help

    Hi all,
    I'm working on this application to create textfields in a page and resize and reposition them as necessary using the mouse(Just like dragging and dropping components in Visual Basic). Is it possible to provide such a functionality for a Textfield in java? If so how? If you do have some reference sites, please let me know. Any help will be appreciated. Thanks.

    Hi,
    if you just need a simple framework:
    I've created a customizer framework for such tasks: Move and resize components with the mouse and allow further customizations. "Snap-to-grid"-feature included! Maybe you find it useful as a base. (It's open source!)
    I started to write a tutorial (still under construction!):
    http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/customizer/index.html
    For adding components see:
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/CustomizerBar.html
    To customize properties use:
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JCustomizerPropertyTable.html
    Register it to the SelectionManager of the JCustomizerPane and set the CustomizableProperties-property of the JCustomizer objects.
    Also have a look at the subclasses of JCustomizer.
    E.g. there are
    customizers for images & shapes:
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JXIconCustomizer.html
    a label customizer with inline editing:
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLabelCustomizer.html
    a line customizer:
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLine2DCustomizer.html
    And there are many classes providing support for menu- and toolbar-actions. (Incuding support for some of the "Java Look and Feel Graphics Repository" actions.)
    Look at the *.swing and the *.swing.action packages.
    Just ask me if you don't find them.
    Homepage:
    http://www.softsmithy.org
    Download:
    http://sourceforge.net/project/showfiles.php?group_id=64833
    Source:
    http://sourceforge.net/svn/?group_id=64833
    http://softsmithy.svn.sourceforge.net/viewvc/softsmithy/trunk/lib/src/org/softsmithy/lib/
    API:
    http://softsmithy.sourceforge.net/lib/docs/api/index.html
    If you have questions just ask me!
    -Puce

  • When typing in the Find Bar, sometimes the caret goes away without clicking or moving the mouse. This also happens when backspacing in the Find Bar, and results in going back one page in the browser. How can this be remedied?

    Sometimes the carat goes away after one letter, while other times I can get an a few letters in before having to re-click inside the text box in the bar.

    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]
    If it does work in Safe-mode then disable all your extensions and then try to find which is causing it by enabling one at a time until the problem reappears.
    * Use "Disable all add-ons" on the [[Safe mode]] start window to disable all extensions.
    * Close and restart Firefox after each change via "File > Exit" (Mac: "Firefox > Quit"; Linux: "File > Quit")

  • Problem of defining value to a textfield in MovieClip

    hello,dear everyone
    there is problem that realy confused me.that is the
    textfield(or other display objects) in MovieClip can't be defined
    when i jumpto that frame.check these simple code:
    mc.stop()
    function goNext(evt:Event){
    mc.nextFrame()
    dosth()
    function dosth()
    if(mc.currentFrame==2)
    mc.mytext.text="hello"
    nextBT.addEventListener("click",goNext)
    the mc is a simple MC that have 2 frames,and the textfield
    object is in the second frame.
    and what i try to do is when i clicked the button,the mc
    jumpto the second frame.and i define a value to that textfield.but
    it's failed when i try to do like that.
    as i debug the program.i found that when i define the value
    to the textfield,that textfield is a Null Object(should be the
    TextField object).not only the textfield not work,but also other
    elements such as Button objects.
    so,i am thinking that must because the objects are too late
    to initialized before they be used.maybe there are some event can
    tell me that all elements has been initialized,as i can use them
    then.what do you think,my friend?

    If all of the code you have is in the first frame, then it
    has processed long before anything ever moved to the second frame.
    What you could try is to have a variables layer that extends
    both frames, and assign the value of the textfield text to that
    variable. Make the textfield associate with that variable (in the
    properties section for it), So when the movieclip moves to the
    second frame the text field should automatically acquire the
    variable value.
    I may not have interpretted your problem correctly, so you
    might have to clarify things if I missed the target.

  • Expanding text fields not moving next fields down the page

    I have a multi-page form with several comment boxes that I want to be expandable (if needed).  I've managed to get them to expand, but the fields following the field that is expanding dynamically are not bumping down the page.  I've gone through and read about different things to try and use (flowed, western, expand to fit, etc), but the fields following the expanding fields are not moving.
    I can send the form I am using to anyone who has a suggestion.  I am confused with the hierarchy and where stuff needs to go in order to work correctly.
    Thanks.

    Hi, it is highly recommended that you create subforms in your form. By creating parts in your form you should create subforms for each of those parts. For the textfield you are trying to make it expandable and flowable to the next page, you must make every of its parents flowed. Your main page is actually set to positioned, even if your subform containing the textfield is flowed, if each of its parents are set to flowed it should work, otherwise it will not flow to next page.
    If you set your page to flowed, it will reposition each of your fields because it is not in subforms. Make sure to create subforms for each parts, putting all fields in subforms. If you set your main page to flowed without creating subforms, all of your fields will be redesigned to be aligned left with the hierarchy order.
    Hope this help.

  • Using a button and a textfield in the same cell of a table

    I have been struggling with this problem for ages, please someone help...
    I am trying to implement a table similar to NetBeans property sheet editor where you have a textfield and a button with "..." in the same table cell. The button is used to invoke a custom editor.
    I have most things working, custom renderers, custom editors and such.
    However, the focus interactions on the table seem completely screwed. Clicking in the editor causes the cell to switch to editing mode as expected. Pressing cursor down or tab, which should close the editor and move focus to the next cell down does not work - the editor closes but the focus disappears to a completely different component elsewhere on my GUI.
    My textfield and button are on a JPanel, and I return that JPanel when getTableCellEditorComponent is called.
    If I switch out the JPanel and instead return the textfield, the focus works as normal.
    I've even looked at the NetBeans source but I can't work out what their trick is.
    Any tips would be gratefully received.
    TIA.

    Thanks for your time, Jeanette...
    Here is a bare-bones example of the problem I'm having. I'm running on JDK1.4 and JDK1.3.1_02.
    I've tried some tricks (hacks) with getNextFocusableComponent and requestDefautFocus and such but with no success.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    * This example shows a keyboard/focus navigation problem when using a JPanel
    * as a table cell editor. The JPanel contains a textfield and a button.
    * Click in the editor to invoke it, and tab-off (or press cursor down). The
    * edit ends, but the focus disappears rather than moving to the next cell in
    * the table.
    * Change the line that returns the panel to return a text field instead, and
    * all is well.
    public class Test
      public static void main( String[] args )
        new Test();
      public Test()
        JFrame f = new JFrame();
        f.setContentPane( new TablePanel() );
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        f.setSize( 800, 600 );
        f.setVisible( true );
      class TablePanel extends JPanel
        TablePanel()
          setLayout( new BorderLayout() );
          JTable table = new JTable();
          table.setDefaultEditor( Object.class, new MyEditor() );
          table.setModel(
            new DefaultTableModel(
              new Object[][]
                {null, null},
                {null, null},
                {null, null},
                {null, null}
              new String[] { "A", "B" } ) );
          add( table, BorderLayout.CENTER );
      class MyEditor extends AbstractCellEditor implements TableCellEditor
        private JComponent myEditorPanel;
        private JTextField myTextField;
        MyEditor()
          myEditorPanel = new MyEditorPanel();
          myTextField = new JTextField();
        public Object getCellEditorValue()
          return null;
        public Component getTableCellEditorComponent( JTable table, Object value,
                                                      boolean isSelected,
                                                      int row, int column )
          return myEditorPanel;   // Problems...
    //      return myTextField;   // Keyboard and focus as expected
      class MyEditorPanel extends JPanel
        JTextField tf;
        MyEditorPanel()
          setLayout( new BorderLayout() );
          tf = new JTextField();
          add( tf, BorderLayout.CENTER );
          add( new JButton( "edit" ), BorderLayout.EAST );

Maybe you are looking for