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

Similar Messages

  • 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

  • Firefox does not paint the window if Windows 7 Basic theme is selected and Fujitsu USB port replicator PR07 is used

    If I use "Windows 7 Basic" theme on my laptop (Fujitsu Lifebook A532), the Firefox window is not painted.
    I see only the border of the window, the content not. As soon as I switch back to the "Windows 7" theme,
    it works again.
    It could be related to the graphics driver (from Intel) of my new laptop.
    Before I had a desktop computer, and did not have this problem.
    Update: the problem occurs only if I use my port replicator (Fujitsu USB Port Replicator PR07).
    If I unplug the replicator, and use only the monitor of my laptop, everything is fine.

    ''When you figure out what's causing your issues, please let us know. It might help other users who have the same problem.''Please create a screenshot of the problem you're seeing by following the guide mentioned at [[How do I create a screenshot of my problem?]].
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. This will help us to visualize the problem.

  • Jscrollbar scrollbar not painting

    I have a jscrollpanel and whenever I populate the panel, the jscrollbar actual scrollbars do not paint until i hover my mouse over them. How would I make it repaint automatically?

    Read the tutorials for working examples.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • JFrame Not Painting Until Resize

    I have a couple of components in my JFrame. At first, it looks like the JFrame's not painting. I tried calling repaint() before and after I made the JFrame visible. I also moved the JFrame, which should repaint it. However, if I try to resize the JFrame or just click while the cursor is in "resize mode," everything draws and acts fine. Unfortunately, I want to make the JFrame non-resizable. What's the problem?

    try calling the validate method before repainting

  • SetSize(int,int) not working in JTextPane.. Please help

    Hi,
    I want to set size of JTextPane so that by default it should show atleast 2 lines.
    I am using setSize(int, int) , but its not working.
    Can anybody help me?

    hi
    From onwards, I will take care of it.. I will put my query in particular category only.
    Actually I tried this one also...
    Following is my method in which I want to set size of JtextPane
    public JPanel initComponents(Vector columnNames, Vector dbNames, Vector data) {
    fieldrefs = new JTextComponent[columnNames.size()];
    JPanel content = new JPanel();
    content.setLayout(new GridBagLayout());
    content.setSize(900,900);
    // Create Menubar
    JMenuBar menuBar = createMenuBar();
    setJMenuBar(menuBar);
    GridBagConstraints gbc = new GridBagConstraints();
    //some code
    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.insets = new Insets(SG_SwingUtilities.BORDER_COMP, // (top, left, bottom, right)
    SG_SwingUtilities.BORDER_COMP, 0, 0);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    JLabel pathLabel = new JLabel(stringPath);
    Font font = new Font(null, Font.BOLD, 12);
    pathLabel.setFont(font);
    content.add(pathLabel, gbc);
    // Insert all the fields.
    for (int i = 0, j = 0; i < columnNames.size(); i++, j += 2) {
    int gridy = i + 1;
    String label = (String) columnNames.elementAt(i); // Name of column.
    gbc = new GridBagConstraints();
    gbc.gridy = gridy;
    gbc.insets = new Insets(SG_SwingUtilities.BORDER_COMP, SG_SwingUtilities.BORDER_COMP, 0, 0);
    gbc.anchor = GridBagConstraints.NORTHWEST;
    content.add(new JLabel(label), gbc);
    if ((i == 4 || i == 5) || (i == 2 && (isMacroNode || isSystemNode))) {
    // tagstart and tagend are expanded in HORIZONTAL direction.
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    if(i==5)
         styledDocEnd = new DefaultStyledDocument();
    fieldrefs[i] = new JTextPane(styledDocEnd);
    }else
    styledDocStart = new DefaultStyledDocument();
    fieldrefs[i] = new JTextPane(styledDocStart);
    if (i == 5) {
         textarea2 = new JTextPane(styledDocEnd); // I want to set this JtextPane size      
    textarea2 = (JTextPane)fieldrefs;
         fieldrefs[i].setSize(100,500);
    tagEndField = new JPanel(new GridBagLayout());
    content.add(tagEndField, gbc);
    normalComponent2 = new JScrollPane(fieldrefs[i]);
    setNormalMode(2);
    // my code
    else {
    // TagStart      
         textarea1 = new JTextPane(styledDocStart); // I want to set this JtextPane size
         textarea1 = (JTextPane)fieldrefs[i];//me
         fieldrefs[i].setSize(100,500);
    tagStartField = new JPanel(new GridBagLayout());
    content.add(tagStartField, gbc);
    normalComponent1 = new JScrollPane(fieldrefs[i]);
    setNormalMode(1);
    /// my code
    fieldrefs[i].addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent me) {
    // DOUBLE (left) CLICK
    if (data != null && !data.isEmpty()) {
    if (data.elementAt(j) != null) {
    String insertData = data.elementAt(j) + "";
    insertData = insertData.replaceAll("\\&\\{\\}", ""); // remove dummy ref
    insertData = insertData.replaceAll("\r", "");
    fieldrefs[i].setText(insertData);
    if(i==4 || i==2)
    insertLineBreaks(textarea1);
    updateColors(textarea1.getText(),true); //me
    if(i==5)
    insertLineBreaks(textarea2);
         updateColors(textarea2.getText(),false); //me
    else if (i == 5) {
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    fieldrefs[i] = new JTextArea(3, 10);
    fieldrefs[i].setForeground(new Color(0, 0, 255));
    // ((JTextArea) fieldrefs[i]).setLineWrap(true);
    if (data != null && !data.isEmpty()) {
    if (data.elementAt(j) != null) {
    String insertData = data.elementAt(j) + "";
    insertData = insertData.replaceAll("\\&\\{\\}", ""); // remove dummy ref
    fieldrefs[i].setText(insertData);
    content.add(new JScrollPane(fieldrefs[i]), gbc);
    else {
    fieldrefs[i] = new JTextArea(2, 10); // description field.
    ((JTextArea) fieldrefs[i]).setLineWrap(true);
    if (data != null && !data.isEmpty()) {
    if (data.elementAt(j) != null) {
    fieldrefs[i].setText(data.elementAt(j) + "");
    content.add(new JScrollPane(fieldrefs[i]), gbc);
    //code
    return content;
    } // initComponents
    protected JTextComponent[] fieldrefs = null; is taken from super class
    Message was edited by:
    ring

  • Non-modal JDialog is not painted and blocks the GUI

    I have developed a GUI that's basically a JFrame with a JDesktopPane.
    The user can, via a menu item, pop up a JDialog that contains some JLists and then select some value from it. Once he/she has done the selection and clicks on OK, the dialog disappears (data processing is then done in the main GUI) and comes back once a specific event has happened. The user then selects other data and so on, until he/she clicks on Cancel, which definitely disposes of the JDialog.
    The graphics of the JDialog are build in the class constructor, which does a pack() but does not make the dialog visible yet. The dialog appears only when doSelection() is called.
         /** Called the first time when user selects the menu item, and then
         when a specific event has happened. */
         public Data[] doSelection() {
              dialog.setVisible(true);
              // ... Code that reacts to user's input. Basically, the ActionListener
              // added to the buttons retrieves the user's selection and calls
              // dialog.setVisible(false) if OK is clicked, or calls dialog.dispose()
              // if Cancel is clicked.
         }Now, everything works fine if the JDialog is modal, but if I make it non-modal only the window decorations of the JDialog are painted, and the control doesn't return to the main GUI. Calling doLayout() or repaint() on the doSelection() has no effect. How can this be fixed?
    I hope I have been able to explain the problem satisfactorily, I could not create a suitable SSCCEE to show you. Thanks in advance for any hint.

    Ok, I've taken some time to think about this problem and I've modified the code a bit.
    Now the dialog shows itself and is responsive (i.e. its JLists can be operated), but the Ok button does not close the dialog as I'd want. I believe that I'm messing up things about threading, and the operations in actionPerformed() should be carried out in another thread, if possible.
    Thanks in advance for any hint / suggestion / comment / insult.
         private Data[] selection;
         /** Constructor */
         public MyDialog() {
              // ... Here is the code that builds the dialog...
              dialog.setModal(false);
              dialog.pack();
              // Note that the dialog is not visible yet
         public Data[] doSelection() {
              operatorAnswer = NONE_YET;
              dialog.setVisible(true);          
              while (operatorAnswer == NONE_YET) {
                   try {
                        wait();
                   } catch (InterruptedException e) { }
              return (operatorAnswer == OK ? selection : null);
         public void actionPerformed(ActionEvent evt) {
              if (okButton.equals(evt.getSource())) {
                   operatorAnswer = OK;
                   retrieveSelection();
                   dialog.setVisible(false);
              else if (cancelButton.equals(evt.getSource())) {               
                   operatorAnswer = CANCEL;
                   dialog.dispose();
         private void retrieveSelection() {
              // ... Here is the code that retrieves selected data from the dialog's JLists
              // and stores it in the "selection" private array...
              notifyAll();
         }

  • JOptionPane not painting correctly in JApplet.

    Having a JOptionPane painting problem in my JApplet.
    applet has a JFrame, that is the "main" container.
    Main frame is already shown. USer clicks a button, and all I'm trying to do is show a simple JOptionPane.
    SPecifically trying to call JOptionPane.showMessageDialog(null, "test message");
    Note the button that generates the event, is on a Panel, within the JFrame.
    I've tried just about everyting I can think of. SwingUtilites.invokeLater ... setting the null to JFrame, applet... and just about everything else...
    JOptionPane does pop up, but the background of the Pane never paints correctly... I've used 1.3.1_04, and 1.4 .. plugins...
    Now at a lost... Read all the newsgroups... and forums..
    But I'm missing somehting?
    Thanks in advace...
    EB.

    check what is in ur paint(Graphic g) method. if it does nothing, remove the paint(Graphic g) method. if it has some codes, double check ur codes.

  • p tags with attributes not removed from JTextPane

    We are using HTMLEditorKit with JtextPane to create a HTML Document Editor, for our project. [JDK 1.3.1.]
    When we have a simple <p> tag for paragraph in HTML and we start deleting things from end of the document, it works fine. But when we have a <P> tag with attributes like <p align='CENTER'> the delete key deletes the characters but the cursor remains in the line below and doesnot move up as the characters of above para get deleted. The HTML also retains the <p align='CENTER'> tag, which should have been removed. It seems its not able to identify <p> tags with attributes as Html para tags, and so not deleting it.
    How do we solve this without migrating to jdk1.4 ? Please help.

    Usually attributes such as 'align=center' are deleted along with a tag, regardless of whether it is a p tag or another one. But you would have to carefully test what exactly gets deleted because attributes are not only stored with paragraphs. They can exist for single characters and as well come from a style sheet.
    The best is to generate a dump of your document before and after deletion.
    You can use something like the below code (it is not optimized at all and thus could be implemented better but it works) to produce a dump
      public void listElements(Element elem, int indent) {
        int i;
        String is = getIndent(indent);
        String elemName = elem.getName();
        Document elemDoc = elem.getDocument();
        String cont = "";
        String theText = "";
        System.out.println(is + "--start-----");
        System.out.println(is + "Element Name:" + elemName);
        if(elemName.equals(new String("content"))) {
          try {
            theText = elemDoc.getText(
                    elem.getStartOffset(),
                    elem.getEndOffset() - elem.getStartOffset());
            System.out.println(is + "Content: " + theText);
            if(theText.indexOf("\r") > -1) {
              System.out.println(is + " plus \\r");
            if(theText.indexOf("\n") > -1) {
              System.out.println(is + " plus \\n");
          catch (Exception e) {
        listAttributes(elem, indent);
        if(!elem.isLeaf()) {
          for(i=0;i<elem.getElementCount();i++) {
            listElements(elem.getElement(i),indent+2);
        System.out.println(is + "---end----");
      public void listAttributes(Element elem, int indent) {
        Object key;
        String attr;
        String attrName;
        int pos;
        String is = getIndent(indent);
        AttributeSet as = elem.getAttributes();
        Enumeration an = as.getAttributeNames();
        try {
          while(an.hasMoreElements()) {
            key = an.nextElement();
            attrName = key.toString();
            attr = as.getAttribute(key).toString();
            System.out.println(is + "Attribute Name: " +
                      attrName + " Attribute Content: " + attr);
            if(attr.indexOf("\r") > -1) {
              System.out.println(is + " plus \\r");
            if(attr.indexOf("\n") > -1) {
              System.out.println(is + " plus \\n");
        catch (Exception e) {
          e.printStackTrace();
      }Hope that helps
    Ulrich

  • Paint bucket tool not painting color on canvas

    Ok - I'm new to photoshop (I just got cs4) and can't seem to get the paint bucket tool to paint the background.  I've started out with a new canvas, selected paint bucket and color from color menu on right side.  Foreground is selected and the paint bucket tool is showing on my cursor - when I click on it over my canvas I expected it to change to the color I selected and it does nothing.  Help??

    I am having the same problem and have checked the mode.  Normal.  Still not working- I have tried eve
    rything includig unlocking the layer- checking the opacity and tolerance.
    using it with other photos and still nothing.

  • Horizantalscroll bar not enabled in JTextPane

    Hi ,
    I have a JTextPane which is added to a JFrame .
    When i try to view a big line of text in JTextPane, horizantal scrollbar is not coming . A Single line is spread into two lines .
    My requirement is to view the text in a single line which should be scrollable .
    Is there any option in JTextPane to set the Columns length .
    Thanks ,
    Rajesh Reddy

    Note that for a scroll bar you need to wrap the text pane in a scroll pane as well (besides just enabling word/line wrap).

  • Can I not paint the background of an image?

    I can draw an image just fine (I use JFrame), but I am having a big problem
    I draw the image, but the image's background color gets drawn over the GUI's. for instance if I have an airplane sprite (.gif or .png), the airplane could be black but the background color of the sprite itself is white. when I g.drawImage(airplane, 200,200,this);, it displays the black airplane along with the rest of the white surrounding that is part of the sprite. I have been able to make up for this so far by doing things like painting the entire GUI white so that you cant tell, but its getting out of hand and unworkable on this new project of mine
    how do I get java to ignore the background color of the sprite itself, and just draw the pixels that are NOT the background color?
    if the image is a black airplane on a white background, I want to be able to just paint the black of the airplane, so it doesn't look like a retarded white square over a blue background (the GUI's background is blue)
    any help is extremely appreciated :-/

    Modify your sprite so it has transparent pixels rather than a background?

  • Can not paint as RGB but appears just CMYK colors

    Hello!
    I would lik to know how to paint in ILLUSTRATOR CS5 RGB colors. All colors here appears as CMYK. But when it was painted not a NEW DOCUMENT, but in PDF of another person, than Illsutrator CS asked to open it as CMYK or RGB and than was posible to paint there RGB colors, but in my NEW DOCUMENT (tryed differend color mode options) RGB paint paints as CMYK.

    Ilvija,
    Have you tried to Move the folder with Illy closed? (you may also just try to press Ctrl+Alt+Shift/Cmd+Option+Shift during startup, but that may not be enough.
    If that does not help, there are more things to try. A less nice solution may be a reinstallation, with the Cleaner Tool included in the process.
    http://www.adobe.com/support/contact/cs5clean.html

  • Paintbrush tool not painting accurately after 10.5.3 update...

    After upgrading to OS X 10.5.3 tonight, I attempted to paint a stroke over a graphic in Motion 3, and no matter how exact my brush stroke was, the stroke was always over too far past the graphic. It's like the crosshair in the brush is off somehow, but only while painting on curved areas. My graphic was a twisted vine that I was attempting to animate over time by using the paint brush stroke as an image mask, but I can no longer get the stroke to paint over the vine image. Anyone else having this strange problem after upgrading? It worked fine earlier today...

    Definitely was not working in 3D...that was actually the first thing I thought of, to check and make sure everything was 2D. I will try to trash preferences and see if that helps.

  • JScrollbar not painting scrollbars until mouseover?

    I have a jscrollpane that has a jtable attached to it, it paints the table just fine, but the jscrollbars do not appear until I mouseover the place where the scrollbar should be. Is there a method I should call that would call the elements of the scrollbar itself? Thanks and happy new year

    Why don't you actually read the reply. Apparently the 70 other people who read your question thought it was a good answer since they had nothing to add.
    It works for everybody else in the forum so all you should need to do is read the tutorial for a working example and then compare your code to see whats different.
    We can't guess why it works for everybody else in the forum and not you. Apparently you are writing some wierd code. You where then asked to post a SSCCE, because we are not mind readers and can't guess what your code looks like.
    I suspect you won't be getting any further help with this question. Maybe you will learn how to post a proper question the next time. And you might learn how not to piss off the only persion who even made an attempt to help solve your problem over the last 5 days.

Maybe you are looking for