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

Similar Messages

  • Center text in a text component with line wrapping

    I need to display dynamic text in a text component. I need line wrapping (on work boundaries) and also need horizontal and vertical center alignment.
    How do I do this? I saw a previous post on aligning text in a JTextArea that said to use a JTextPane but I don't see in JTextPane how to do word wrapping.
    Thanks,
    John

    //  File:          SystemInfoWindow.java.java
    //  Classes:     SystemInfoWindow
    //  Package:     utilities.msglib
    //  Purpose:     Implement the SystemInfoWindow class.
    //     Author:          JJB 
    //     Revision History:
    //     Date            By   Rel#  Description of change
    //     =============  ===  ====  ===============================================
    //     Jul 3, 2006   JJB  1.00  Original version
    //  Public Types / Classes          Type Description
    //  ========================     =============================================
    //     SystemInfoWindow
    package utilities.msglib;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    * TODO Enter description
    class SystemInfoWindow extends JDialog {
          * @param args
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        Test thisClass = new Test();
                        thisClass.setVisible(true);
                        SystemInfoWindow window = new SystemInfoWindow(thisClass);
                        window.setMessage("System shutdown in progress ... lot sof atatarte athis tis a sa logoint of tesxt it keeps going and going and going thsoreoiat afsjkjslakjs fshafhdskrjlkjsdfj");
                        window.setVisible(true);
         //     ------------------------  Inner Classes ---------------------
         static class Test extends JFrame {
              private JPanel jContentPane = null;
               * This is the default constructor
              public Test() {
                   super();
                   initialize();
               * This method initializes this
               * @return void
              private void initialize() {
                   this.setSize(300, 200);
                   this.setContentPane(getJContentPane());
                   this.setTitle("JFrame");
               * This method initializes jContentPane
               * @return javax.swing.JPanel
              private JPanel getJContentPane() {
                   if (jContentPane == null) {
                        jContentPane = new JPanel();
                        jContentPane.setLayout(new BorderLayout());
                   return jContentPane;
         //     ------------------------  Static Fields ---------------------
         private static final long serialVersionUID = -8602533190114692294L;
         //     ------------------------  Static Methods --------------------
         //     ------------------------  Public Fields ---------------------
         //     ------------------------  Non-Public Fields -----------------
         private JPanel jContentPane = null;
         private JTextPane textField = null;
         public SystemInfoWindow(JFrame frame) {
              super(frame);
              initialize();
              //setUndecorated(true);
              setLocationRelativeTo(frame);
              pack();
         //     ------------------------  Interface Implementations ---------
         //     ------------------------  Public Methods --------------------
         public void setMessage(String text){
              textField.setText(text);
              adjustSize();
         //     ------------------------  Non-Public Methods ----------------
         private void adjustSize(){
              Dimension oldSize = textField.getPreferredSize();
              textField.setPreferredSize(new Dimension(
                        oldSize.width, oldSize.height + 30));
              pack();
         //     ------------------------  Generated Code --------------------
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setModal(true);
              this.setContentPane(getJContentPane());
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowOpened(java.awt.event.WindowEvent e) {
                        //setLocationRelativeTo(MsgLibGlobals.parent);
                        pack();
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.setMaximumSize(new java.awt.Dimension(50,2147483647));
                   jContentPane.add(getTextField(), java.awt.BorderLayout.CENTER);
              return jContentPane;
          * This method initializes textField     
          * @return javax.swing.JTextPane     
         private JTextPane getTextField() {
              if (textField == null) {
                   textField = new JTextPane();
                   textField.setEditable(false);
                   textField.setMaximumSize(new java.awt.Dimension(20,2147483647));
              return textField;
    }Message was edited by:
    BaltimoreJohn

  • How to highlight a line in a text stream and position the cursor at the end.

    I would like to select a line in a text control data stream, highlight the text, and place the cursor at the end of the line so that the text control can be edited at that point.

    Depends on what you mean by "highlight". If you mean highlight in the sense of when you use the mouse to select text, then you can't do that and then place the cursor at the end, since that would effectively "unhighlight" the text. You need to use a different kind of "highlight", like turning the text bold or something. This KB article talks about highlighting particular characters: How Do I Highlight Particular Characters in a String Control?
    See attached for simple example. Modify as needed.
    Attachments:
    Text Select.vi ‏19 KB

  • Output text component new line

    HI Team,
    I am picking up a value from resouce bundle for output text component.
    I wish to display data in output text component to display data after a new line.
    Suppose the message is coming as How are you.Welcome
    Now it should come as
    How are you
    Welcome
    Any help how is this achievable.
    I am working on Jdev 11.1.1.6
    Regards,
    Ajay

    Hi Team,
    The issue is resolved now.
    I have changed the escape property of output text component. to false so as to avoid the <br /> being HTML-escaped. and at the value level have used like
    <af:outputText value="#{XX.YOUR_REQUEST_HAS_BEEN_SUBMITTE}&lt;br />&lt;br />#{XX.YOUR_REQUEST_HAS_BEEN_SUBMITTE1}"
                                         id="ot10" escape="false"/>
    Where XX.YOUR_REQUEST_HAS_BEEN_SUBMITTE=Value1 and YOUR_REQUEST_HAS_BEEN_SUBMITTE1=Value2 in my resource bundle file.
    Output is coming as
    Value1
    Value2
    Does any one know how can i mark it as correct , can't see it after the forums upgrade to new one.
    Message was edited by: Ajay

  • Adobe Reader highlight tool no longer filling text, just creating a line around the text

    The Highlight tool in Adobe reader is no longer working as it used to.  Instead of filling the text, as it used to, the tool just creates a line around the text.  This makes the highlights much harder to spot.
    I'm running Win 8 and using Adobe Reader XI version 11.0.09.
    I've attached a screenshot to illustrate.  The way the tool used to work, they way I want it to, is shown by all the highlighted text in the document.  The way it currently works, is shown on the first line of text , where a portion of the text has been highlighted using the tool as it works now.  I just creates a yellow line around the text.
    I've checked the way the highlight settings are on both the old highlighted text and the new text and they appear identical.  Both the colour and opacity percentage settings are the same.
    Very frustrated.  Any help appreciated.

    Gilad D (try67) wrote:
    Very strange. I'm not sure what the reason for this behaivour is, but try right-clicking one of the previous highlights and selecting "Make Current Properties Default". Then try to create a new highlight...
    Did that.  No effect.

  • Custom text component with different start and end points for each line

    I'm trying to create a custom component extending textArea in which each individual line in the textArea would have different start and end points.  For example, the start/end points for line 1 might be 20 pixels in the front and 35 pixels at the end but start/end points for line 2 might be 25 pixels in front and 20 pixels at the end, etc.  These boundary values would be passed in.  The width of the entire textArea component would be a fixed size.  The result would be something like this:
         Jack and Jill
              ran up the hill
      to fetch a pail of water
    depending on the boundary values of each individual line of course.  The custom component would take a string and render it in the text component with the appropriate individual line start and end points.  I'm trying to do this by adding the text component to the display with the passed in string and then adding in spaces in the beginning of each line and adding a "/n" at the end of the line wherever appropriate based on the start and end values for that line.
    Just wondering if I'm on the right track and if anyone has any advice on this.

    > Applying the marker places the same icon on all lines of the graph and I need a different one for each
    What do you have selected when you assign the marker? It
    shouldn't apply to all the markers on the whole graph unless you have all the existing markers selected when you apply the new one.
    Assigning marker designs is exactly analogous to assigning bar graph designs.
    If you have a single marker selected when you assign the new design, it will apply to only that graph data point.
    If you use the group select tool (or option-click with the direct select tool) to reclick on an already-selected marker until all the markers for the same line are selected, and then assign a design, the new design will apply only to the selected line. (You can extend the graph by adding more rows, and the new data points will inherit the marker for the line they are on.)
    The thread linked to below demonstrates in more detail how the marker designs are scaled:
    http://www.adobeforums.com/cgi-bin/webx/.3bc10970/0

  • How to email text from a text component in my applet on a the host server ?

    How to email text from a text component in my applet on a the host server, back to my email address ?
    Assuming I have Email Form on the host server.
    Help will be appreciated.

    You can do like below
    =REPLACE(Fields!Column.Value," " & Parameters!ParameterName.value & " ","<b>" & Parameters!ParameterName.value & "</b>")
    The select the expression and  right click and choose placeholder properties
    Inside that set Markup type as HTML 
    then it will highlight the passed parameter value in bold within the full xml string
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Word processing within a text component

    Although this is a potentially great application, I am at present prevented from using it to create a website due to the lack, as far as I can determine, of any form of processing individual text within the text components e.g. making individual words or word groups bold or italic or giving them COLORS.
    I have large informatory text areas on my pages which need this sort of processing in order to avoid client eyestrain as well as my own.
    Of course one can get around this to some extent by using multiple components but for long texts this quickly becomes very tedious and error prone, especially if one wants to copy from another source.
    The Static Text component, which I presume is meant for this sort of text, in it's present simple form allows word wrap but no line formatting. The basic Text Area component (multiple lines) has no word wrap but does allow line formatting. However when one sets the Read Only property, it seems that any self created line formatting is duly destroyed. This is strangely not the case with the old Standard Mutliline Text Area component.
    I may be missing something but if not I hope that these features may yet be incorporated.
    Regards,
    Dave

    You can use static text to render pure HTML, just set "escape" property to false.
    Note that the HTML text must be well former.
    Regards.

  • How to create a text Component With Certain Properties

    I need to create a text component with the following properties:
    Has Capability to be italic, right/left aligned, have different background / foreground colors, and most importantly, the ability to have a fixed width and a height that is set by the amount of text in it (ie line wrapping expands the field vertically).
    It should be a simple exercise, but I cannot seem to figure out how to do it.

    Here is the correct syntax :
    private static JEditorPane constructPane(String text, int normWidth, int normHeight, boolean rightAlign, boolean italic,boolean isWhite) {
              JEditorPane pane = new JEditorPane();
              pane.setEditable(false);
              pane.setContentType("text/html");
              pane.setText(
                   "<html><head></head><body>"
                   + (italic?"<i>":"")
                   + "<table><COLGROUP><COL width=\""+normWidth+"\"><THREAD><tr><td valign=\"top\" align="+(rightAlign?"\"right\"":"\"left\"")+">"
                   + text+"</td></tr></table>"
                   + (italic?"</i>":"")
                   + "</body></html>");
              pane.setSize(normWidth,normHeight);
              if(isWhite)
                   pane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1,0,1,0,Color.WHITE),BorderFactory.createEmptyBorder(0,1,0,1)));
                   pane.setForeground(Color.WHITE);
              else {
                   pane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1,0,1,0,Color.BLACK),BorderFactory.createEmptyBorder(0,1,0,1)));
                   pane.setForeground(Color.BLACK);
              return pane;
         }

  • Formatting HTML Text in Text component

    Hi all,
    I'm trying to render some Html text in a text component, I'm
    getting the HTML from within an xml document as such:
    <xml><htext><p><b>Testing HTML
    Text</b></p><p>Here's another
    line.</p></htext></xml>
    If I put that into a Text component with the htmlText=htext
    property, the line spacing is as expected, but it seems to add in a
    blank space character for every character of the html code. (E.g.
    "<b>Testing" adds 3 extra spaces before the word "Testing").
    Renders like (using - as space character):
    Testing HTML Text
    -Here's another line.
    If I use the condeseWhite=true property on the Text
    component, it fixes the extra space characters issue, but then
    stuffs the line spacing up, so <p> becomes rendered like a
    <br>.
    Renders like:
    Testing HTML Text
    Here's another line.
    Any thoughts, or help is much appreciated, thanks in advance.
    Oz
    P.S I was trying to avoid the obvious "br" tag which will
    make it work and render correctly....
    <p><b>Testing HTML Text</b></p>
    <br/><p>Here's another line.</p>

    no. use css.

  • Choice of Text Component

    Hi!
    I need the text component for image and text or only the text output. I also need scrolling, if it is needed, and auto line wrapping.
    In general, I need multiline JLabel with scrolling, line and word wrapping.

    HowdyTom.Sanders:
    where in the formatting help does it tell you how to embed links in the text rather than having to use the ugly URL?To see how it's done, click reply to camickr's post, then click quote original -- basically the format is:
    [ url link] whatever [ /url] (tag with no space).
    ;o)
    V.V.

  • Reduce Space Btween Lines In  A Text Box

    I have a very large text box in my report and inorder to fit everything on 1 page, I need to reduce the space between the lines in the text box.
    I have tried highlighting the text and then Format/Text Spacing/Custom and setting this to various number, including zero, but cannot get the space small enough.
    Any pointers appreciated
    Gus

    Custom spacing 0 is the same as single and is the smallest you can get.

  • Implementing a Text Component

    Hi all, I have to implement a custom text component for a
    project im working on. I was hoping someone could give me
    some direction on how to implement the text storage.
    I wont need more than the regular 256 ascii characters and
    text sizes could reach 4+ megs.
    1 - an array list of bytes
    2 - a stringbuffer
    3 - a LONG string
    I was thinking about doing every line as an arraylist of bytes
    and then putting the line objects into an arraylist - as opposed
    to a contiguous list of bytes.
    that way moving through the data will be easier.
    As well, im most interested in knowing how they implement the
    actual component. I was going to draw the characters (im using
    custom fonts) onto a bufferedimage and then display them onto
    a custom component that will be a JPanel with a drawn on scrollbar
    that will control the drawing bounds.
    i was hoping someone with a knowledge of how Java implements
    text components could give a brief comment on how
    text is stored in memory and drawn on to the screen in a
    text component - id be forever grateful!
    i hear a lot of people say they read the Java source code but i
    wouldnt even know where to begin in such a process, lol.
    thanks!

    Secondly, I don't really understand what you are doing or
    why you feel you need to create a custom component to display textIm working on a mathematics project.
    There is an equation editor that has to be integrated with
    graphics routines (graphs, models etc).
    This JPanel will have keypresses mapped to symbols and
    special functions with the "text" formatted around the embedded
    graphics.
    The implementation will be easy - BUT it did get me curious
    on how the JVM implements a text component.
    From the internal representation (maybe stringbuffers?) to
    how it converts each Unicode char and then paints it into
    the component.
    After all looking up each char and then decoding the TrueType
    format (which i read uses a Virtual Machine with instruction sets)
    and drawing it (directly to the component or to an image?) seems
    like it would be intensive - but text components always seem
    very fast.

  • Forcing a text component to lose focus

    I have several JTables and JTextFields in my GUI, and when I click somewhere off of any of them, I would like the one that has focus (if there is one) to lose its focus. The only way I know of to do this is to call transferFocus(), but if I do that, another text component will grab the focus, and I don't want that.
    One thing that seems to work is to disable the components when focus is transferred... then focus will not be grabbed. However, I don't want to leave these components in a constantly disabled state... then I would have to enable them again at the instant they are clicked on.
    Anyone have any suggestions?

    My requirement is that when empty space is clicked on, the component needs to lose focus. So it isn't like another text component is taking over the focus... I want nothing to be focused on.
    To better explain my situation, my GUI is a graph of nodes connected by lines. Each node has a few text fields and a JTable. When the user clicks on the background between the nodes, the node should be unselected and the focus should be removed.

  • Highlighting the text by changing the "character fill color" with double-spacing?

    Highlighting the text by changing the "character fill color" doesn't seem to go well with double-spacing.
    Has anyone been aware of this issue?
    Try double-spacing the text you highlighted. What's up with this?
    This is so annoying and frustrating. I've been trying to do both of them for like 2-3 hours.
    You CAN do both, of course, but if you double-space the highlighted text, it just creates this huge highlighted part (it highlights the space between the two lines!) below the actual text.
    Anyone help me pleeeeeeeease.

    In Pages v5.2.2, taking Baskerville Regular 12 pt, and double-spacing it with character fill color does produce a nasty effect. With View > Show Rulers, I looked where the lines of text lined up on the vertical scale.
    Then I changed the Spacing selector from Lines to Between. Now, just the text had the character fill color, but the line height had increased visually downward. With the between setting, line height is changed to points, and indicates 27 pt. If you adjust this value to 16 pt, the second line of double-spacing will realign with where it was before the between change, while retaining discrete line character fill color.
    Before: Spacing set to Lines, and 2.0 - Double.
    After: Spacing set to Between, and 16 pt

Maybe you are looking for

  • IOS 7.1.2 screwed up

    Folks, While updating iOS 7.1.2 on my iPhone 5, the phone got hanged almost midway. Has been like that for last 10 hours or so... Can not even reboot fix it or hard-reset it as the power button doesn't work due to a manufacturing defect. Can somebody

  • Aluminium keyboard update not working

    Hey everyone! So when I got my mac mini (mid 2011 model), I purchased a third party keyboard with it. I had this Apple Aluminium Keyboard Update, which is supposed to improve battery life on the keyboard, stuck on my launchpad, but when I tried to in

  • Sql query related to beaking the string based on string postion

    Hi, I have coloumn in this way city_state texas tx sanantanio tx newyork ny newjersy nj newyork newjersy landon 1000 I want to get the last characters after the space from the string(eg: texas tx) only tx, that means i want to only break the strings

  • Use new hdd to increase space in specific folder?

    Hey guys, I just installed a new 2TB harddrive and I have an old 300GB drive where all my downloaded TV shows go. Now those 300GB are never enough and I want the folder where the 300GB drive is mounted in (~/down) to be bigger. Naturally, the simples

  • Documentation on creating an Adobe form

    Dear Expert, I am new to the Adobe form. I tried to follow the guideline in help.sap to create a relocation service. However i am getting a lots or error. Do anyone have any documentation on Adobe including tutorial? Thanks. Regards, Bryan