JTextPane Line Highlighting

Hi.
I have a JTextPane, and I would like to make it highlight a whole row, or line, that the cursor is on.
I DON'T want to set the selection color. I want the current row that is selected to highlight the background of the text for the whole width of the row, then unhighlight it when it is deselected.
Please help.
Thanks!

Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

Similar Messages

  • JTextPane and highlighting

    Hello!
    Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
    Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtTest = new JTextPane(doc);
         private Random random = new Random();
         private void appendLong() throws BadLocationException {
              String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
              int start = doc.getLength();
              doc.insertString(doc.getLength(), str, null);
              int end = doc.getLength();
              txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
         private Color randomColor() {
              int r = intRand(0, 255);
              int g = intRand(0, 255);
              int b = intRand(0, 255);
              return new Color(r, g, b);
         private int intRand(int low, int hi) {
              return random.nextInt(hi - low + 1) + low;
         }As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
    I can fix this problem by changing the insert line to this:
    doc.insertString(doc.getLength()+1, str, null);With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
    I've tried in veign to hack that newline character away. For example:
              if (doc.getLength() == 0) {
                   doc.insertString(doc.getLength(), str, null);
              } else {
                   doc.insertString(doc.getLength()+1, str, null);
              } But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
    I've also tried:
    txtTest.setText(txtTest.getText()+str);That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
    I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!

    It may work but it is nowhere near the correct
    solution.It seems to me the "correct" solution would be for Sun to fix the issue, because it seems they are secretly inserting a newline character into my Document. Here's a compilable program that shows what I mean:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultHighlighter;
    import javax.swing.text.DefaultStyledDocument;
    public class TestFrame extends JFrame {
         private JButton btnAppend = new JButton("Append");
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtPane = new JTextPane(doc);
         private Random random = new Random();
         public TestFrame() {
              setSize(640, 480);
              setLocationRelativeTo(null);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        dispose();
              getContentPane().add(new JScrollPane(txtPane), BorderLayout.CENTER);
              getContentPane().add(btnAppend, BorderLayout.SOUTH);
              btnAppend.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doBtnAppend();
         private void doBtnAppend() {
              try {
                   String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
                   int start = doc.getLength();
                    * This line causes all highlights to have the same color,
                    * but the text correctly starts on the first line.
                   doc.insertString(doc.getLength(), str, null);
                    * This line causes all highlights to have the correct
                    * (different) colors, but the text incorrectly starts
                    * on the 2nd line.
    //               doc.insertString(doc.getLength()+1, str, null);
                    * This if/else solution causes the 2nd appended text to
                    * incorrectly start on the 2nd line, instead of being
                    * concatinated with the existing text on the first line.
                    * (a newline character is somehow inserted after the first
                    * line)
    //               if (doc.getLength() == 0) {
    //                    doc.insertString(doc.getLength(), str, null);
    //               } else {
    //                    doc.insertString(doc.getLength()+1, str, null);
                   int end = doc.getLength();
                   txtPane.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
              } catch (BadLocationException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new TestFrame().setVisible(true);
         private Color randomColor() { return new Color(intRand(0, 255), intRand(0, 255), intRand(0, 255)); }
         private int intRand(int low, int high) { return random.nextInt(high - low + 1) + low; }
    }Try each of the document insert lines in the doBtnAppend method and watch what it does. (comment out the other 2 of course)
    It wastes resources and is inefficient. A lot of work
    goes on behind the scenes to create and populate a
    Document.I tracked the start and end times in a thread loop to benchmark it, and most of the time the difference is 0 ms. When the document gets to about 7000 characters I start seeing delays on the order of 60 ms, but I'm stripping off text from the beginning to limit the max size to 10000. It might be worse on slower computers, but without a "correct" and working solution it's the best I can come up with. =)

  • JTextPane &  XML highlighter

    Hello,
    I wrote an XML Viewer via JTextPane.
    Unfortunately I don't know how to implement a good XML highlighter.
    I wrote an own code using the regulary expression.
    With the regulary expression I can get the "startPosition" and "endPosition"
    of pattern I am searching for within a text.
    StyledDocument xmlDoc;
    xmlDoc.setCharacterAttributes(startPosition, length,  style, true);It is working very good for xml files up to ca. 1000 ... 1200 lines.
    But for bigger files it takes too long until the highlighting took place.
    1) Is there another faster mechanism to highlight xml files?
    2) How do I wrap / unwrap the horizontal display without re-reading or re-highlighting the xml file again?
    Thanks Aykut

    Interesting. I will keep that in mind.
    I have more or less got what i need working now - just smoothing out some bumps.
    Extending DefaultHighlighter cannot help much as to override paint() is near impossible because required info is private in the superclass :(
    But I could hold my own highlight info there for one highlight type and paint those first before calling super.paint(). Looking back, I should have replaced the whole highlight system - that would have been easier and neater.

  • JTextPane Colour Highlighting

    Im doing up a prototype of a compiler, i have certain keywords like "if"s and "elses" etc etc which i would like to be colour coded differently!!! My problem is when i have big files the time it takes to colour code and display is horrendous!!! I just want to know am i going about the right way in highlighting my keywords?? is there a better way or how can i improve my current code!!! any suggestions at all are welcome!! heres a sample of code..
    public class MyDoc extends DefaultStyledDocument
    static MutableAttributeSet setAttr, ifAttr, defaultAttr;
    public MyDoc()
    setAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(setAttr, Color.red);
    ifAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(ifAttr, Color.blue);
    defaultAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(defaultAttr, Color.black);
    public void insertString(int offs, String str, AttributeSet a) throws
    BadLocationException
    if (str == null) return;
    StringTokenizer tokenizer = new StringTokenizer(str," \n",true);
    try
    while( tokenizer.hasMoreTokens())
    String token = (String)tokenizer.nextElement();
    if(token.length() == 0)
    continue;
    if (token.compareTo("set") == 0)
    super.insertString(offs, token, setAttr);
    } else if (token.compareTo("if") == 0)
    super.insertString(offs, token, ifAttr);
    } else
    super.insertString(offs,token, defaultAttr);
    offs = offs + token.length();
    } catch (BadLocationException ble)
    System.err.println("MyDoc::insertString()"+ble.toString());
    }catch(Exception e)
    System.err.println("MyDoc::insertString()"+e.toString());
    bottom line is that im looking for some other way, more elegant way of getting keywords highlighted, the above is nasty!!!
    cheers people,
    JB.

    I have tried a couple of different approaches for using threads:
    1) Load the data into the text pane and then use a thread for highlighting. The highlighting got messed up if you type data in the text pane while the highlighting thread is working. This approach won't work with the current structure of the SyntaxDocument.
    2) Load data into the text pane in smaller pieces. This approach shows a little more promise as the text pane is shown with initial data in a couple of seconds. However, the entire load time goes from 15 to 26 seconds. During this 26 second load time you can type data and scroll, but the text pane reacts very slowly. I haven't verified that data inserted into the document by typing does not cause problems with data being loaded into the document by the background thread. (Swing components are not thread safe, but hopefully insertion of data into the document is). Here is the test class:
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class LoadTextPane extends JFrame
         char[] data;
         JTextPane textPane;
         public LoadTextPane(String fileName)
              EditorKit editorKit = new StyledEditorKit()
                   public Document createDefaultDocument()
                        return new SyntaxDocument();
              textPane = new JTextPane();
             textPane.setEditorKitForContentType("text/java", editorKit);
             textPane.setContentType("text/java");
              JScrollPane sp = new JScrollPane(textPane);
              getContentPane().add( sp );
              long startTime = new Date().getTime();
              try
                   File f = new File( fileName );
                   FileReader in = new FileReader( f );
                   int size = (int) f.length();
                   data = new char[ size ];
                   int chars_read = 0;
                   while( chars_read < size )
                        chars_read += in.read( data, chars_read, size - chars_read );
                   in.close();
                   long endTime=new Date().getTime();
                   System.out.println( "File size: " + chars_read );
                   // System.out.println( data );
              catch (IOException sse)
                   System.out.println("Error has occured"+sse);
              System.out.println( "Time to read file: " + (new Date().getTime() - startTime ));
              if (data.length > 8092)
                   Thread load = new LoadThread(data, textPane.getDocument());
                   load.start();
              else
                   textPane.setText( new String(data, 0, data.length) );
         public static void main( String[] args )
              String fileName = "c:/java/jdk1.3/src/java/awt/Component.java";
              JFrame f = new LoadTextPane(fileName);
              f.setDefaultCloseOperation( EXIT_ON_CLOSE );
              f.setSize( 1000, 600);
              f.setVisible(true);
         class LoadThread extends Thread
              char[] data;
              Document doc;
              LoadThread(char[] data, Document doc)
                   this.data = data;
                   this.doc = doc;
              public void run()
                  int start = 0;
                  int end = data.length;
                  int increment = 8192;
                   long begin = System.currentTimeMillis();
                  while ( start < end )
                       if (start + increment > end)
                            increment = end - start;
                       String text = new String(data, start, increment);
                       try
                            doc.insertString(doc.getLength(), text, null);
                       catch(BadLocationException e)
                            System.out.println(e);
                       start += increment;
                        //  allow some time for the gui to process typed text, scrolling etc
    //                    try { Thread.sleep(300); }
    //                    catch (Exception e) {}
                   System.out.println( "Load Text Pane: " + (System.currentTimeMillis() - begin) );
    }

  • Problems with JTextPane line wrapping

    Hi to all.
    I'm using a code like this to make editable a figure that I paint with Java 2D. This JTextPane don't has a static size and for that, the text in it cannot be seen affected by the natural line wrap of the JTextPane component. The problem is that I have to set a maximun size for the JTextPane and I want to use the line wrap only when the width of the JTextPane be the maximun width. How can I do this?
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Dimension d = getPreferredSize();
                d.width += 10;
                setSize(d);
            public void removeUpdate(DocumentEvent e) {
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }Thanks for read.

    I'm working hard about that and I can't find the perfect implementation of this. This is exactly what I want to do:
    1. I have a Ellipse2D element painted into a JPanel.
    2. This ellipse is painted like a circle.
    3. Into the circle there's a text area, that user use to name the cicle.
    4. The text area is a JTextPane.
    5. When the user insert a text area, it can increase it size, but it can't be bigger than the circle that it contains.
    6. There is a maximun and a minimun size for the circle.
    7. When the user write into de JTextPane, it grows until arriving at the limit.
    8. When the JTextPane has the width size limit, if the user writes more text into it, the JTextPane write it into another line.
    9. The size of the JTextPane has to be the optimun size, it cannot have empty rows or empty lines.
    This code does all this except 9, cause if the user remove some text of the text area, the form of the JTextPane changes to a incorrect size.
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                //If it has the maximun width and the maximun height, the user cannot
                //write into the JTextPane
                /*AbstractDocument abstractDoc;
                if (doc instanceof AbstractDocument) {
                abstractDoc = (AbstractDocument) doc;
                abstractDoc.setDocumentFilter(new DocumentSizeFilter(this, 15));
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Runnable doRun = new Runnable() {
                    public void run() {
                        int MAX_WIDTH = 200;
                        Dimension size = getSize();
                        Dimension preferred = getPreferredSize();
                        if (size.width < MAX_WIDTH) {
                            size.width += 10;
                        } else {
                            size.height = preferred.height;
                        setSize(size);
                SwingUtilities.invokeLater(doRun);
            public void removeUpdate(DocumentEvent e) {
                this.setSize(this.getPreferredSize());
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }I know that the problem is into the removeUpdate method, but I have to set to the JTextPane, allways the optimun size, how can I do this?
    Thanks to all.
    Edited by: Daniel.GB on 06-jun-2008 18:32

  • Monitor color off - PDF text lines highlighted

    When I open any PDF file, my monitor wallpaper becomes pixelated and changes colors and looks like a negative.  The lines of text in the file are either blacked out or highlighted with other colors.  I have had tech support clean my computer system today and remove any viruses but the problems still exist.  SJZ

    Refer to your Gateway manual. Usually there are settings for color adjust that are independent of the computer or other driving source. You can probably get a warmer color setting in this way.

  • Line highlighting in Text Component

    I'm trying to figure out how to apply a colored background to certain lines of a text component. This is common, for instance, in a lot of editors, especially IDE's (notably, Eclipse), where the currently selected line has a separate background color from the rest of the page. I'm having a lot of trouble understanding how to use Elements and Views and EditorKits and all that, and I'm not even sure if that will solve the problem. All I've been able to do so far is put a colored background behind individual characters; but then it stops at the end of the line, instead of continuing for the width of the text component.
    Any help is greatly appreciated.

    I assumed you were using the built-in Highlighter classes to do the coloring. If you aren't, you're doing a lot more work than you need to. Here's what I use:import java.awt.Color;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.*;
    * Usage: new CurrentLineHighlighter(myColor).install(myTextComponent);
    public class CurrentLineHighlighter implements ChangeListener
      static final Color DEFAULT_COLOR = new Color(0, 0, 0, 15);
      private Highlighter.HighlightPainter painter;
      private Object highlight;
      private JTextComponent comp;
      public CurrentLineHighlighter()
        this(null);
      public CurrentLineHighlighter(Color highlightColor)
        Color c = highlightColor != null ? highlightColor : DEFAULT_COLOR;
        painter = new DefaultHighlighter.DefaultHighlightPainter(c);
      public void install(JTextComponent tc)
        comp = tc;
        comp.getCaret().addChangeListener(this);
      public void stateChanged(ChangeEvent evt)
        if (highlight != null)
          comp.getHighlighter().removeHighlight(highlight);
          highlight = null;
        int pos = comp.getCaretPosition();
        Element elem = Utilities.getParagraphElement(comp, pos);
        int start = elem.getStartOffset();
        int end = elem.getEndOffset();
        try
          highlight = comp.getHighlighter().addHighlight(start, end, painter);
        catch (BadLocationException ex)
          ex.printStackTrace();
    }

  • Current line highlighting in editor

    In JDev 9.0.4.0, build 1419 there is a bug in highlighting of current line. The color of current line is always default, regardless to the color set in preferences. When you turn off highlighting of current line, it behaves even worse.

    I assumed you were using the built-in Highlighter classes to do the coloring. If you aren't, you're doing a lot more work than you need to. Here's what I use:import java.awt.Color;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.text.*;
    * Usage: new CurrentLineHighlighter(myColor).install(myTextComponent);
    public class CurrentLineHighlighter implements ChangeListener
      static final Color DEFAULT_COLOR = new Color(0, 0, 0, 15);
      private Highlighter.HighlightPainter painter;
      private Object highlight;
      private JTextComponent comp;
      public CurrentLineHighlighter()
        this(null);
      public CurrentLineHighlighter(Color highlightColor)
        Color c = highlightColor != null ? highlightColor : DEFAULT_COLOR;
        painter = new DefaultHighlighter.DefaultHighlightPainter(c);
      public void install(JTextComponent tc)
        comp = tc;
        comp.getCaret().addChangeListener(this);
      public void stateChanged(ChangeEvent evt)
        if (highlight != null)
          comp.getHighlighter().removeHighlight(highlight);
          highlight = null;
        int pos = comp.getCaretPosition();
        Element elem = Utilities.getParagraphElement(comp, pos);
        int start = elem.getStartOffset();
        int end = elem.getEndOffset();
        try
          highlight = comp.getHighlighter().addHighlight(start, end, painter);
        catch (BadLocationException ex)
          ex.printStackTrace();
    }

  • JTextPane line number restriction

    I want all the text I type to appear in just two lines in the JTextPane. How do I achive that ?

    This problem would be solved ,if we are able to find the current row of the editor.So I triyed like this and the o/p I get is 0 !!
    (Place this code inside kePressed/keyTyped)
    DefaultStyledDocument dc=(DefaultStyledDocument)yourTextPane.getStyledDocument();
    Element root=dc.getDefaultRootElement();
    int row=root.getElementIndex(yourTextPane.getCaretPosition());
    System.out.println(">>>>>   "+row+" Caret.... "+yourTextPane.getCaretPosition());Pls suggest where I went wrong.
    Thanks

  • Modifying Edges - Why are ALL lines highlighted??

    I just upgraded to Flash CS6 yesterday, and am trying to work on an animation project.
    Whenever I use the Select Tool to modify the edges of a Paintbrush stroke, or a Pencil line, ALL of the lines in the image are highlighted as I bend the edge this way and that.
    I'd prefer for the outline highlight to only show up on the area I'm actually modifying.
    I find this default behavior really distracting, and I can't figure out how to turn it off.

    If you are using normal mergable shape mode,curves when selected has dotted grid pattern to indicate the selection.However if all the lines are getting selected that means they are all connected.Switch to subselection tool and see if all the lines are connected. In case you dont want different lines to merge on intersection then use object drawing mode.However if you you want to continue with normal shape mode and want only outlines to be displayed,you can choose View>Preview modes>Outlines(CTRL+SHIFT+ALT+O on WIN/CMD+SHIFT+OPT+O on MAC)).Hope this hhelps

  • JTextPane selection Highlighting

    I have got a next problem.
    I have got text editor that uses JTextPane. When I select text and try change font (choose ComboBox with Font names) my text selection is hide and I mush execute textPane.grabFocus(); to take back selection.
    How can I make so as this selection is not hide?

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=317332

  • How to highlight entire line

    I am currently implementing an IDE. I try to highlight entire line(not only text but also following blank field) when users set a breakpoint on that line.
    Using Highlighter.addhighlight(start, end, HighlightPainter) only allow me to highlight the text part in the line. I haven't figure out how to do that.
    Any helps are appreciated.

    one way to highlight a full line or draw a breakpoint
    symbol on a particular is to create a custom highlight
    painter and override the paint method. If you want to
    highlight the full line then use the width from the
    JTextArea and only the y coordinate and height from
    the view coordinates.
    If you would like a breakpoint symbol and a particular
    line then just put a drawImage call in the paint method
    which draws an icon on that line
    I've included some code for custom painter for both
    highlighting a full line and rendering a breakpoint
    icon.
         private class     SingleLineHighlighterPainter      extends DefaultHighlighter.DefaultHighlightPainter {
                   public     SingleLineHighlighterPainter( Color color )
                   {     super( color );          }
         * Paints a highlight over a single line.
                   * just uses the first point a work around only
         * @param g the graphics context
         * @param offs0 the starting model offset >= 0
         * @param offs1 the ending model offset >= offs1
         * @param bounds the bounding box for the highlight
         * @param c the editor
              public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) {
                        Rectangle alloc = bounds.getBounds();
                             Rectangle area = c.getBounds();
                             try {
                        // --- determine locations ---
                                       TextUI mapper = c.getUI();
                                       Rectangle p0 = mapper.modelToView(c, offs0);
                        // --- render ---
                                       Color color = getColor();
                                       if (color == null) {
                                       g.setColor(c.getSelectionColor());
                                       else {
                                       g.setColor(color);
                        // render using just the y coordinates and height from the initial point
                                       g.fillRect(0, p0.y, alloc.width, p0.height);
                             catch (BadLocationException e) {
                        // can't render
         private class     BreakpointPainter      extends DefaultHighlighter.DefaultHighlightPainter {
                        public     BreakpointPainter()
                        {     super( Color.green );          }
              * Paints a breakpoint image
                        * just uses the first point a work around only
              * @param g the graphics context
              * @param offs0 the starting model offset >= 0
              * @param offs1 the ending model offset >= offs1
              * @param bounds the bounding box for the highlight
              * @param c the editor
                   public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) {
                             Rectangle alloc = bounds.getBounds();
                                  Rectangle area = c.getBounds();
                                  try {
                             // --- determine locations ---
                                            TextUI mapper = c.getUI();
                                            Rectangle p0 = mapper.modelToView(c, offs0);
                                            Image im = ( (ImageIcon) Icons.stopSignIcon ).getImage();
                             // render using just the y coordinates and height from the initial point
                                            g.drawImage( im,0,p0.y+2,null );          
                                  catch (BadLocationException e) {
                             // can't render
    to use these do the following
         DefaultHighlighter dh = new DefaultHighlighter();
              dh.setDrawsLayeredHighlights( false );
              SingleLineHighlighterPainter     dhp = new SingleLineHighlighterPainter(Color.green);
              BreakpointPainter                    bpp = new BreakpointPainter();
              buff.setHighlighter(dh);
              try {
                   dh.addHighlight(25, 30, dhp);     // single line highlighter here
                   dh.addHighlight(60, 60, bpp);     // add breakpoint highlighter here
                   dh.addHighlight(120,120,bpp);     // add breakpoint highlighter here
              catch (javax.swing.text.BadLocationException jst) { };
              buff.setMargin( new Insets( 0,20,0,0 ) );
    where numbers used with the addHighlight method are
    the location within the model. In this case the
    addHighlight( 25,30, dhp ) will highlight the line with
    a view location corresponding to position 25 in
    the model. So just need to specify any model location
    on the line you want to highlight.
    Setting breakpoints is the same just need one model
    position on the line where you want the image to be
    drawn.
    Hope that's clear.
    Also helps to look at the source code for
    DefaultHighlighter.java.
    eric
    [email protected]

  • Highlighting text in  Preview

    Unexpectedly, a strange alteration to how I can highlight text,  when reading a pdf in Preview has occurred. I used to be able to check the highlight icon in the annotations bar and that's about it. Now when I intend to highlight text, the colour extends to being four lines wide, and when I finish - it gets even stranger. Instead of  the text with a straight band of colour - like with a real high-liner pen - odd shapes occur across the text! How to revert to a simple, colour line highlighting the text I feel is important?

    No it has nothing to do with, if the PDF is protected or not. It is not in this case, it is having the PDF open in Preview and holding down the mouse button and dragging and highlighting the information in whatever direction you push your mouse in. Preview seems to only highlight what ever is showing on the screen instead of highlighting from page to page.

  • Removing Ken Burns effect once photo is on time line

    I am using the lastest version of iMovie, I have made a movie using only photos. All of the photos have the Ken Burn's effect some are ok but other are not. Can the Ken Burn's effect be turned off once images are on the time line?

    Found it. Select the photo on time line, highlight the adjust symbol in the upper right hand corner, highlight crop button and chose "fit" or "crop to fill".

  • Grid lines in numbers, how do you switch them on and off?

    I am having trouble getting the grid lines to show in numbers, the format has grid lines highlighted in blue but switching this off or on has no effect on grid lines in the sheet

    Hi algebra,
    I got an email notification of your reply, but this page has not yet updated. This forum software sometimes is out of sync with the emails.
    Numbers 3.2
    Click on the 'bullseye' top left of the table to select the whole table
    In the format panel on the right of the Numbers window, click on Cell
    Border > Line style, Width (I prefer 1pt), Colour (I prefer Black) , border pattern (I prefer to set them all the same, see below)
    Regards,
    Ian.

Maybe you are looking for