Line Number in JTextPane

Hi Experts;
How do I add a caret listener on this code so that it will just add a number
when the user goes to the next line.
import java.awt.*;
import javax.swing.*;
public class LineNumber extends JComponent
     private final static Color DEFAULT_BACKGROUND = new Color(213, 213, 234);
     private final static Color DEFAULT_FOREGROUND = Color.white;
     private final static Font DEFAULT_FONT = new Font("arial", Font.PLAIN, 11);
     // LineNumber height (abends when I use MAX_VALUE)
     private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
     // Set right/left margin
     private final static int MARGIN = 5;
     // Line height of this LineNumber component
     private int lineHeight;
     // Line height of this LineNumber component
     private int fontLineHeight;
     // With of the LineNumber component
     private int currentRowWidth;
     // Metrics of this LineNumber component
     private FontMetrics fontMetrics;
      * Convenience constructor for Text Components
     public LineNumber(JComponent component)
          if (component == null)
               setBackground( DEFAULT_BACKGROUND );
               setForeground( DEFAULT_FOREGROUND );
               setFont( DEFAULT_FONT );
          else
               setBackground( DEFAULT_BACKGROUND );
               setForeground( DEFAULT_FOREGROUND );
               setFont( component.getFont() );
          setPreferredSize( 99 );
     public void setPreferredSize(int row)
          int width = fontMetrics.stringWidth( String.valueOf(row) );
          if (currentRowWidth < width)
               currentRowWidth = width;
               setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
     public void setFont(Font font)
          super.setFont(font);
          fontMetrics = getFontMetrics( getFont() );
          fontLineHeight = fontMetrics.getHeight();
      * The line height defaults to the line height of the font for this
      * component. The line height can be overridden by setting it to a
      * positive non-zero value.
     public int getLineHeight()
          if (lineHeight == 0)
               return fontLineHeight;
          else
               return lineHeight;
     public void setLineHeight(int lineHeight)
          if (lineHeight > 0)
               this.lineHeight = lineHeight;
     public int getStartOffset()
          return 4;
     public void paintComponent(Graphics g)
           int lineHeight = getLineHeight();
           int startOffset = getStartOffset();
           Rectangle drawHere = g.getClipBounds();
           g.setColor( getBackground() );
           g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
           g.setColor( getForeground() );
           int startLineNumber = (drawHere.y / lineHeight) + 1;
           int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
           int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
           for (int i = startLineNumber; i <= endLineNumber; i++)
           String lineNumber = String.valueOf(i);
           int width = fontMetrics.stringWidth( lineNumber );
           g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
           start += lineHeight;
           setPreferredSize( endLineNumber );
} Thanks for your time . . .
The_Developer

Here's what I use. It behaves correctly WRT wrapped lines, and should work equally well with a JTextArea or a JTextPane.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.SizeSequence;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
* LineNumberView is a simple line-number gutter that works correctly
* even when lines are wrapped in the associated text component.  This
* is meant to be used as the RowHeaderView in a JScrollPane that
* contains the associated text component.  Example usage:
*<pre>
*   JTextArea ta = new JTextArea();
*   ta.setLineWrap(true);
*   ta.setWrapStyleWord(true);
*   JScrollPane sp = new JScrollPane(ta);
*   sp.setRowHeaderView(new LineNumberView(ta));
*</pre>
* @author Alan Moore
public class LineNumberView extends JComponent
  // This is for the border to the right of the line numbers.
  // There's probably a UIDefaults value that could be used for this.
  private static final Color BORDER_COLOR = Color.GRAY;
  private static final int WIDTH_TEMPLATE = 99999;
  private static final int MARGIN = 5;
  private FontMetrics viewFontMetrics;
  private int maxNumberWidth;
  private int componentWidth;
  private int textTopInset;
  private int textFontAscent;
  private int textFontHeight;
  private JTextComponent text;
  private SizeSequence sizes;
  private int startLine = 0;
  private boolean structureChanged = true;
   * Construct a LineNumberView and attach it to the given text component.
   * The LineNumberView will listen for certain kinds of events from the
   * text component and update itself accordingly.
   * @param startLine the line that changed, if there's only one
   * @param structureChanged if <tt>true</tt>, ignore the line number and
   *     update all the line heights.
  public LineNumberView(JTextComponent text)
    if (text == null)
      throw new IllegalArgumentException("Text component cannot be null");
    this.text = text;
    updateCachedMetrics();
    UpdateHandler handler = new UpdateHandler();
    text.getDocument().addDocumentListener(handler);
    text.addPropertyChangeListener(handler);
    text.addComponentListener(handler);
    setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
   * Schedule a repaint because one or more line heights may have changed.
   * @param startLine the line that changed, if there's only one
   * @param structureChanged if <tt>true</tt>, ignore the line number and
   *     update all the line heights.
  private void viewChanged(int startLine, boolean structureChanged)
    this.startLine = startLine;
    this.structureChanged = structureChanged;
    revalidate();
    repaint();
  /** Update the line heights as needed. */
  private void updateSizes()
    if (startLine < 0)
      return;
    if (structureChanged)
      int count = getAdjustedLineCount();
      sizes = new SizeSequence(count);
      for (int i = 0; i < count; i++)
        sizes.setSize(i, getLineHeight(i));
      structureChanged = false;
    else
      sizes.setSize(startLine, getLineHeight(startLine));
    startLine = -1;
  /* Copied from javax.swing.text.PlainDocument */
  private int getAdjustedLineCount()
    // There is an implicit break being modeled at the end of the
    // document to deal with boundary conditions at the end.  This
    // is not desired in the line count, so we detect it and remove
    // its effect if throwing off the count.
    Element map = text.getDocument().getDefaultRootElement();
    int n = map.getElementCount();
    Element lastLine = map.getElement(n - 1);
    if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
      return n;
    return n - 1;
   * Get the height of a line from the JTextComponent.
   * @param index the line number
   * @param the height, in pixels
  private int getLineHeight(int index)
    int lastPos = sizes.getPosition(index) + textTopInset;
    int height = textFontHeight;
    try
      Element map = text.getDocument().getDefaultRootElement();
      int lastChar = map.getElement(index).getEndOffset() - 1;
      Rectangle r = text.modelToView(lastChar);
      height = (r.y - lastPos) + r.height;
    catch (BadLocationException ex)
      ex.printStackTrace();
    return height;
   * Cache some values that are used a lot in painting or size
   * calculations. Also ensures that the line-number font is not
   * larger than the text component's font (by point-size, anyway).
  private void updateCachedMetrics()
    Font textFont = text.getFont();
    FontMetrics fm = getFontMetrics(textFont);
    textFontHeight = fm.getHeight();
    textFontAscent = fm.getAscent();
    textTopInset = text.getInsets().top;
    Font viewFont = getFont();
    boolean changed = false;
    if (viewFont == null)
      viewFont = UIManager.getFont("Label.font");
      changed = true;
    if (viewFont.getSize() > textFont.getSize())
      viewFont = viewFont.deriveFont(textFont.getSize2D());
      changed = true;
    viewFontMetrics = getFontMetrics(viewFont);
    maxNumberWidth = viewFontMetrics.stringWidth(String.valueOf(WIDTH_TEMPLATE));
    componentWidth = 2 * MARGIN + maxNumberWidth;
    if (changed)
      super.setFont(viewFont);
  public Dimension getPreferredSize()
    return new Dimension(componentWidth, text.getHeight());
  public void setFont(Font font)
    super.setFont(font);
    updateCachedMetrics();
  public void paintComponent(Graphics g)
    updateSizes();
    Rectangle clip = g.getClipBounds();
    g.setColor(getBackground());
    g.fillRect(clip.x, clip.y, clip.width, clip.height);
    g.setColor(getForeground());
    int base = clip.y - textTopInset;
    int first = sizes.getIndex(base);
    int last = sizes.getIndex(base + clip.height);
    String text = "";
    for (int i = first; i <= last; i++)
      text = String.valueOf(i+1);
      int x = MARGIN + maxNumberWidth - viewFontMetrics.stringWidth(text);
      int y = sizes.getPosition(i) + textFontAscent + textTopInset;
      g.drawString(text, x, y);
  class UpdateHandler extends ComponentAdapter
      implements PropertyChangeListener, DocumentListener
     * The text component was resized. 'Nuff said.
    public void componentResized(ComponentEvent evt)
      viewChanged(0, true);
     * A bound property was changed on the text component. Properties
     * like the font, border, and tab size affect the layout of the
     * whole document, so we invalidate all the line heights here.
    public void propertyChange(PropertyChangeEvent evt)
      Object oldValue = evt.getOldValue();
      Object newValue = evt.getNewValue();
      String propertyName = evt.getPropertyName();
      if ("document".equals(propertyName))
        if (oldValue != null && oldValue instanceof Document)
          ((Document)oldValue).removeDocumentListener(this);
        if (newValue != null && newValue instanceof Document)
          ((Document)newValue).addDocumentListener(this);
      updateCachedMetrics();
      viewChanged(0, true);
     * Text was inserted into the document.
    public void insertUpdate(DocumentEvent evt)
      update(evt);
     * Text was removed from the document.
    public void removeUpdate(DocumentEvent evt)
      update(evt);
     * Text attributes were changed.  In a source-code editor based on
     * StyledDocument, attribute changes should be applied automatically
     * in response to inserts and removals.  Since we're already
     * listening for those, this method should be redundant, but YMMV.
    public void changedUpdate(DocumentEvent evt)
//      update(evt);
     * If the edit was confined to a single line, invalidate that
     * line's height.  Otherwise, invalidate them all.
    private void update(DocumentEvent evt)
      Element map = text.getDocument().getDefaultRootElement();
      int line = map.getElementIndex(evt.getOffset());
      DocumentEvent.ElementChange ec = evt.getChange(map);
      viewChanged(line, ec != null);
}

Similar Messages

  • How can I put line number into JTextPane?

    Most editors has ability that shows line numbers begining of each lines.
    The line number doesn't effect any content in the editor, however.
    I'm using JTextPane for editor, and I want to show line number for each line.
    How can I do this?

    have a look at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=258176
    ?

  • 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

  • Updating the Line number on status bar.

    Hi all,
    I have developed an editor using swing, however I have used the JTextpane class to display the text. I had did of trouble with features such as go to line as this class does not support methods such as getLineCount in the JTextArea class. However I over came this by writing the method shown below.
    The problem is that I want to show the current line number on the status bar. When do I call this method? After every '\n'?
    The setLine Number method is below.
    Thanks for your help
    Ciara
    public void setLineNumber(int num) {
    int lineNum = 1;
    int lastNewline = 0;
    char text[] = editor.getText().toCharArray();
    if (num < 1)
    return;
    if (num == 1) {
    editor.setCaretPosition(0);
    return;
    int i;
    for (i = 0; i < text.length; i++) {
         if (text[i] == '\n') {
         lastNewline = i;
         lineNum++;
         if (num == lineNum) {
         editor.requestFocus();
         editor.setCaretPosition(lastNewline + 1);
         return;
    }     

    Perhaps extending a PlainDocument is better, if line
    numbers are meaningful for your application.
    About your method, mind that getText can be quite dear,
    so it is better not to call it if you don't need it.
    For a more efficient alternative, look at Document.getText(int offset, int length, Segment txt)It uses a Segment (un unguarded string) pointing directly
    into the document, which you can use much like a char
    array.
    As to your question, I would define a CaretListener
    so as to update the status bar when the caret moves.

  • How to implement Line number in JTextArea

    Hi
    I have seen some JTextArea with Line numbers How to do it
    Thankx

    I'm playing around with trying to make a Line Number component that will work with JTextArea, JTextPane, JTable etc. I'm not there yet, but this version works pretty good with JTextArea. At least it will give you some ideas.
    Good luck.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class LineNumber extends JComponent
         private final static Color DEFAULT_BACKGROUND = new Color(230, 163, 4);
         private final static Color DEFAULT_FOREGROUND = Color.black;
         private final static Font DEFAULT_FONT = new Font("monospaced", Font.PLAIN, 12);
         // LineNumber height (abends when I use MAX_VALUE)
         private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
         // Set right/left margin
         private final static int MARGIN = 5;
         // Line height of this LineNumber component
         private int lineHeight;
         // Line height of this LineNumber component
         private int fontLineHeight;
         private int currentRowWidth;
         // Metrics of this LineNumber component
         private FontMetrics fontMetrics;
         *     Convenience constructor for Text Components
         public LineNumber(JComponent component)
              if (component == null)
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( DEFAULT_FONT );
              else
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( component.getForeground() );
                   setFont( component.getFont() );
              setPreferredSize( 9999 );
         public void setPreferredSize(int row)
              int width = fontMetrics.stringWidth( String.valueOf(row) );
              if (currentRowWidth < width)
                   currentRowWidth = width;
                   setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
         public void setFont(Font font)
              super.setFont(font);
              fontMetrics = getFontMetrics( getFont() );
              fontLineHeight = fontMetrics.getHeight();
         * The line height defaults to the line height of the font for this
         * component. The line height can be overridden by setting it to a
         * positive non-zero value.
         public int getLineHeight()
              if (lineHeight == 0)
                   return fontLineHeight;
              else
                   return lineHeight;
         public void setLineHeight(int lineHeight)
              if (lineHeight > 0)
                   this.lineHeight = lineHeight;
         public int getStartOffset()
              return 4;
         public void paintComponent(Graphics g)
              int lineHeight = getLineHeight();
              int startOffset = getStartOffset();
              Rectangle drawHere = g.getClipBounds();
    //          System.out.println( drawHere );
    // Paint the background
    g.setColor( getBackground() );
    g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
              // Determine the number of lines to draw in the foreground.
    g.setColor( getForeground() );
              int startLineNumber = (drawHere.y / lineHeight) + 1;
              int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
              int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
    //          System.out.println( startLineNumber + " : " + endLineNumber + " : " + start );
              for (int i = startLineNumber; i <= endLineNumber; i++)
                   String lineNumber = String.valueOf(i);
                   int width = fontMetrics.stringWidth( lineNumber );
                   g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
                   start += lineHeight;
              setPreferredSize( endLineNumber );
         public static void main(String[] args)
              JFrame frame = new JFrame("LineNumberDemo");
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              JPanel panel = new JPanel();
              frame.setContentPane( panel );
              panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
              panel.setLayout(new BorderLayout());
              JTextArea textPane = new JTextArea();
              JScrollPane scrollPane = new JScrollPane(textPane);
              panel.add(scrollPane);
              scrollPane.setPreferredSize(new Dimension(300, 250));
              LineNumber lineNumber = new LineNumber( textPane );
              lineNumber.setPreferredSize(99999);
              scrollPane.setRowHeaderView( lineNumber );
              frame.pack();
              frame.setVisible(true);

  • JEditorPane - getting Selected Text or Active Line number

    Is there any predefined method that will give me the current line selected or the line at which the cursor is?
    I am displayed a piece of java code in my JEditorPane, the user can browse through the entire file.. and I need to call an event when a user selects/double clicks a particular module name or based on the current line number where the cursor is. Is there any simple technique to get the line number or the current highlighted text?
    I am relatively new to JEditorPane. Also If you think I shoudl go upon writing an actionListener, a mouse of keyboard... please let me know how to go about it. I keep getting confused.
    Thanks,
    Sirish

    In the future, Swing related questions should be posted in the Swing forum.
    there any simple technique to get the line number Well, a JEditorPane is typically used for displaying HTML. So does a line number make sense when you don't know the contents of the HTML. If you simply have lines of text then you should be using a JTextArea or a JTextPane.
    Check out this posting for a method to return the line number at a give caret postion:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
    or the current highlighted text?Read the API. A get??? method will do what you want.

  • Displaying line numbers in JTextPane?

    Hi I have attached a JTextPane to an InternalFrame. What i wanted to do is i have to display line number on the left side of the textpane and that should be not editable(only Line number) and when we move to the next line the cursor has to be placed right next to the line number. How this can be done?

    You can try this one http://www.developer.com/java/other/article.php/3318421/Add-Line-Numbering-in-the-JEditorPane.htm
    Or this http://java-sl.com/bullets_numberings.html (bullets/numbering based)
    Or this http://tips4java.wordpress.com/2009/05/23/text-component-line-number/

  • Delivery schedule line number in make to order

    Hi all,
    i am doing make to order scenario with 20 strategy group. In sales order we r defining the different delivery schedule lines.when i run the MRP and getting the plan orders for all the FG material and semifinished material, the sale order number and sale order item number is getting updated in production order . Beside these two , delivery schedule line number is not populated and delivery date is not picking correctly in production order.
    please give your valuable suggestion .
    i would be highly thankful to u
    regards
    piyush

    Hi
    When you do the MRP Run at MD02, maintain the Delivery Schedules as 3 (schedule lines), so when ever you do the MRP Run, it will run along with the delievry date.
    reward if it helps
    Regards
    Prasanna R

  • Delivery schedule line number in sales order is not populated in production

    Hi all,
    i am doing make to order scenario with 20 strategy group. In sales order we r defining the different delivery schedule lines.when i run the MRP and getting the plan orders for all the FG material and semifinished material, the sale order number and sale order item number is getting updated in production order . Beside these two , delivery schedule line number is not populated in production order.
    please give your valuable suggestion .
    i would be highly thankful to u
    Will reward points.
    Regards
    Kumaraguru

    Hi Kumar,
    Some changes done in your PRD server.If yes then contact abap consultant regarding the same.
    Because these type of problem comes when you do transport or changes done in the system.
    Regards,
    Anil

  • Delivery schedule line number in sales order is not populated  in productio

    Hi all,
    i am doing make to order scenario with 20 strategy group. In sales order we r defining the different delivery schedule lines.when i run the MRP and getting the plan orders for all the FG material and semifinished material, the sale order number and sale order item number is getting updated in production order . Beside these two , delivery schedule line number is not populated in production order.
    please give your valuable suggestion .
    i would be highly thankful to u
    Regards
    Kumaraguru

    Hi Kumar,
    Some changes done in your PRD server.If yes then contact abap consultant regarding the same.
    Because these type of problem comes when you do transport or changes done in the system.
    Regards,
    Anil

  • Link between schedule Line Number and Delivery

    Is there a link between Schedule line Number and Delivery number ?
    Eg. Line item 10 with quantity 100. 
    has 5 schedule lines..with 5 different delivery dates.
    1 .  quanity 40
    2.   quantity 30
    3.   quantity 20
    4.   quanity  6
    5    quantity  4
    For schedule line 1, 2 deliveries were created,
    one      with quantity 20
    another with quantity 15
    quantity 5 is still not delivered.
    also schedule lines 2,3,4 and 5 are fully delivered.
    Is there any table, FM etc in SAP which will give me the link between the schedule line and delivery number ?
    Total deliveries created : 6. - But which delivery corresponds to which schedule line ?
    Please dont tell me to look VGBEL and VGPOS.. that will just give line item number 10.. I need to get the schedule line number.
    Also, RV_SCHEDULE_CHECK_DELIVERIES --> will give me the delivered quantity against each schedule line.
    My purpose is to create an ontime delivery report .
    a report which list each schedule lines, and tell, how many shipments were late/ontime/early etc..
    and for Late ones, how many days late has to be found.
    this is where i need the delivery.
    No. Of days Late = Actual GI Date - Planned GI Date.
    Actual GI date is in the delivery.
    Any suggestions ?
    Thank you in advance.

    Hi,
    Check in the below link.
    relation between VBEP-ETENR and LIKP-VBELN
    Thanks,
    Sree.

  • Delivery schduline line number in make to order

    Hi all,
    i am doing make to order scenario with 20 strategy group. In sales order we r defining the different delivery schedule lines.when i run the MRP and getting the plan orders for all the FG material and semifinished material, the sale order number and sale order item number is getting updated in production order . Beside these two , delivery schedule line number is not populated and delivery date is not picking correctly in production order.
    please give your valuable suggestion .
    i would be highly thankful to u
    regards
    piyush

    Hi
    When you do the MRP Run at MD02, maintain the Delivery Schedules as 3 (schedule lines), so when ever you do the MRP Run, it will run along with the delievry date.
    reward if it helps
    Regards
    Prasanna R

  • Schedule line number determination - Schedule line category CP(MRP)

    Hello All,
    I want to know on what basis schedule line numbers getting determined.
    Schedule line category: CP-MRP
    Sales order line items getting confirmed based on the Planned order--> production order created through MRP run.
    I have created sales order line item 1 with 100 quantities. for example I created today. RDD also today.
    3 production order created.
    Those production orders confirmation date as below.
    Production order 1 - 60 quantities - 14.04.2014
    Production order 2 - 30 quantities - 16.04.2014
    Production order 3: 10 quantities - 18.02.2014.
    There are four schedule lines for the line item 1.
    All the 4 lines showed as per the confirmation date order.
    But the schedule line numbers are not as per the above order.
    For example,
    Schedule line number   ----- delivery date ----- Confirmed qty
    1.                                         09.04.2014            0
    3.                                         14.04.2014            60
    2                                          16.04.2014           30
    4                                          18.04.2014            10
    On what basis this schedule numbers getting determined? Is there any standard procedure ?
    Why schedule line numbers not inline with the confirmed date?
    Let me know if you need more information.
    Thank you.
    Regards,
    Rakkimuthu C

    Hi,
    Schedule line number is the number that uniquely identifies the schedule line .
    Use When an item has more than one schedule line, the system automatically assigns a unique number to each line. The number is displayed in the details screens for schedule lines.
    Note The schedule line number serves internal purposes and does not, for example, determine the sequence of schedule lines in the overview screen. The schedule lines on the overview screen are sorted by date.
    The schedule line number will get created automatically by the system. I hope this will clarify your doubt. Thanking you.

  • Line number in JEditorPane

    I would like to know the line number of the current caret position in a JEditorPane. The getLineOfOffset(int offset) method in JTextArea offers exactly what I want. How come there's no method to find out about line number in JEditorPane?
    As a workaround, I copied the Swing code from the JTextArea.getLineOfOffset method and used it in my class which extends from JEditorPane. It seems to work fine, but it feels like a bad hack. Will the JTextArea code always work in JEditorPane? Any alternatives? I just think that it's tedious and inefficient to deal with StringTokenizer or manually searching for new line charactors on CaretEvent's.
        public int getLineOfOffset(int offset) throws BadLocationException {
            Document doc = getDocument();
            if (offset < 0) {
                throw new BadLocationException("Can't translate offset to line", -1);
            } else if (offset > doc.getLength()) {
                throw new BadLocationException("Can't translate offset to line", doc.getLength()+1);
            } else {
                Element map = getDocument().getDefaultRootElement();
                return map.getElementIndex(offset);
        }

    It's not a hack. Any document used with a Swing text component is supposed to have the same basic element structure, i.e., a default root element whose children represent logical lines. It's just that with some kinds of documents, like HTML, line numbers don't really mean anything. But JTextArea is hard-coded to use a PlainDocument, which means a logical line always represents a paragraph (or a line of code, or something meaningful), so it made sense for it to provide those convenience methods.

  • Line number in a *.class file, please help, advanced language guys

    dear all,
    i use c++ to open a *.class file and try to read line number of code in the file, i have 2 questions:
    1. i read line number in a method successfully, but i can not understand the meaning of start_pc, following are one of those data, please explain:
    s = start_pc,n = line_number
    s , n
    0 , 123
    8 , 125
    23 , 126
    29 , 127
    34 , 129
    38 , 130
    2. i can not find where the class's line number are, i.e. class start line and class end line, or field's line number.
    does these info exist inside a *.class file?
    thx for any light

    jdb gets line number of fields from class file, not
    source file definitely.I'm not really sure how you tested this, but here's my test, and JDB definitely gets its listing from the source file.
    First, I created and compiled class Tester:
    public class Tester
        public static void main( String[] argv )
        throws Exception
            Tester x = new Tester();
            System.out.println(x.toString());
        int     x;
        int     y;
        private Tester()
            x = 0;
            y = 1;
    }Then, I ran this in JDB. Note lines 16 and 17 in the output from "list":
    H:\Workspace>jdb Tester
    Initializing jdb ...
    stop in Tester.mainDeferring breakpoint Tester.main.
    It will be set after the class is loaded.
    runrun Tester
    Set uncaught java.lang.Throwable
    Set deferred uncaught java.lang.Throwable
    >
    VM Started: Set deferred breakpoint Tester.main
    Breakpoint hit: "thread=main", Tester.main(), line=12 bci=0
    12            Tester x = new Tester();
    main[1] list
    8    {
    9        public static void main( String[] argv )
    10        throws Exception
    11        {
    12 =>         Tester x = new Tester();
    13            System.out.println(x.toString());
    14        }
    15
    16        int     x;
    17        int     y;
    main[1] quit
    Tester@b82368Then I edited the source file. Again, look at lines 16 and 17:
    H:\Workspace>jdb Tester
    Initializing jdb ...
    stop in Tester.mainDeferring breakpoint Tester.main.
    It will be set after the class is loaded.
    runrun Tester
    Set uncaught java.lang.Throwable
    Set deferred uncaught java.lang.Throwable
    >
    VM Started: Set deferred breakpoint Tester.main
    Breakpoint hit: "thread=main", Tester.main(), line=12 bci=0
    12            Tester x = new Tester();
    main[1] list
    8    {
    9        public static void main( String[] argv )
    10        throws Exception
    11        {
    12 =>         Tester x = new Tester();
    13            System.out.println(x.toString());
    14        }
    15
    16        int     a;
    17        int     b;
    main[1]

Maybe you are looking for

  • How to stop a Scheduler Job in Oracle BI Publisher 10g

    Hello! Can someone tell me how can I stop a scheduler job in Oracle BI Publisher 10g? I scheduled a bursting job to run a report but is running during two days. I would like to stop it. Thanks. Edited by: SFONS on 19-Jan-2012 07:16

  • Capturing footage from Canon XH A1

    Hi All - I'm a bit new to Final Cut Express but ran across the following problem: When I try to capture footage from my Canon XH A1 HD video camera, FCE does not recognize that there's any connection or that the camera is plugged into my MacBook Pro

  • Call Function

    Hi,   Can any one detail the exact difference between Call Function and Call Function in Update Task. Regards, Sreedhar

  • [SOLVED] gnome 3 look and feel

    Hello all, I did a fresh install of arch and gnome 3 last night.  I am currently running on fallback mode, prefer that mode to the new interface.  The question I have is, is it possible to easily customize/theme Gnome 3 Fallback in Arch to change som

  • What's the best way to convert between pixels and device-independent units?

    WHAT I HAVE: Visual Basic 2010, .NET 4.0, WinForms WHAT I NEED: I need a way to convert back and forth between device-dependent units (i.e., pixels) and device-independent units (i.e., inches, centimeters, points). The VB6Compatibility namespace has