Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: How To: Add line numbers to your JTextArea

  1. #1
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    814
    My Mood
    Devilish
    Thanks
    7
    Thanked 99 Times in 86 Posts

    Default How To: Add line numbers to your JTextArea

    Well, I know a few people have wanted to do things like this before. So here is my code approach to it, enjoy. There are other methods I'm sure, but I think this is the easiest.

    It makes use of the JScrollPane Row Header

    import java.awt.Color;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Element;
     
     
    public class LineNumbering extends JFrame{
    	private static JTextArea jta;
    	private static JTextArea lines;
     
    	public LineNumbering(){
    		super("Line Numbering Example");
    	}
     
    	public static void createAndShowGUI(){
    		JFrame frame = new LineNumbering();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		JScrollPane jsp = new JScrollPane();
    		jta = new JTextArea();
    		lines = new JTextArea("1");
     
    		lines.setBackground(Color.LIGHT_GRAY);
    		lines.setEditable(false);
     
    		jta.getDocument().addDocumentListener(new DocumentListener(){
    			public String getText(){
    				int caretPosition = jta.getDocument().getLength();
    				Element root = jta.getDocument().getDefaultRootElement();
    				String text = "1" + System.getProperty("line.separator");
    				for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++){
    					text += i + System.getProperty("line.separator");
    				}
    				return text;
    			}
    			@Override
    			public void changedUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void insertUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void removeUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    		});
     
    		jsp.getViewport().add(jta);
    		jsp.setRowHeaderView(lines);
    		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     
    		frame.add(jsp);
    		frame.pack();
    		frame.setSize(500,500);
    		frame.setVisible(true);
    	}
     
    	public static void main(String[] args){
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
    	}
    }

    Chris
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

  2. The Following 5 Users Say Thank You to Freaky Chris For This Useful Post:

    AdiRat (February 23rd, 2010), Bubumuk (March 3rd, 2011), JavaPF (September 17th, 2009), Json (September 11th, 2009), neo_2010 (September 30th, 2009)


  3. #2
    Junior Member
    Join Date
    Jul 2009
    Location
    SomeWhere in the world
    Posts
    27
    Thanks
    1
    Thanked 10 Times in 5 Posts

    Default Re: How To: Add line numbers to your JTextArea

    very good one...thanks a lot
    On the way to be Master...

  4. #3
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    814
    My Mood
    Devilish
    Thanks
    7
    Thanked 99 Times in 86 Posts

    Default Re: How To: Add line numbers to your JTextArea

    Glad you guys like it, would you like me to see about adding line highlighting when you click the line number and things?

    Regards,
    Chris
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

  5. #4
    Junior Member
    Join Date
    Sep 2009
    Posts
    9
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: How To: Add line numbers to your JTextArea

    Thanks !!!

  6. #5
    Junior Member
    Join Date
    Feb 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How To: Add line numbers to your JTextArea

    This very useful code. Also, that line highlighting sounds pretty interesting... If you have enough time, can you implement it, please?

    Thanks you very much

  7. #6
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    814
    My Mood
    Devilish
    Thanks
    7
    Thanked 99 Times in 86 Posts

    Default Re: How To: Add line numbers to your JTextArea

    OK, so this seemed to be a popular code snippet, and with a request of highlighting i have decided to actually do it. Sorry it took so longer but here it is.

    import java.awt.Color;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.MouseInputListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Element;
    import javax.swing.text.Highlighter;
     
     
    public class MainWindow extends JFrame implements MouseInputListener, DocumentListener, FocusListener{
    	private JTextArea jta;
    	private JTextArea lines;
    	private Highlighter highlighter;
     
    	public MainWindow(){
    		super("Line Numbering & Highlighter Example");
    	}
    	public void createAndShowGUI(){
    		/* Set up frame */
    		JFrame frame = new MainWindow();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		/* Set up JtextArea */
    		jta = new JTextArea();
    		jta.getDocument().addDocumentListener(this);
     
    		/* Set up Highlighter */
    		highlighter = jta.getHighlighter();
     
    		/* Set up line numbers */
    		lines = new JTextArea("1");
    		lines.setBackground(Color.LIGHT_GRAY);
    		lines.setEditable(false);
    		lines.addMouseListener(this);
    		lines.addFocusListener(this);
     
    		/* Set up scroll pane */
    		JScrollPane jsp = new JScrollPane();
    		jsp.getViewport().add(jta);
    		jsp.setRowHeaderView(lines);
    		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     
    		jta.setText("Hello world how are you today!");
     
    		/* pack and show frame */
    		frame.add(jsp);
    		frame.pack();
    		frame.setSize(500,500);
    		frame.setVisible(true);
    	}
     
    	/* Document Listener Events */
    	public void changedUpdate(DocumentEvent de) {
    		lines.setText(getText());
    	}
    	public void insertUpdate(DocumentEvent de) {
    		lines.setText(getText());
    	}
    	public void removeUpdate(DocumentEvent de) {
    		lines.setText(getText());
    	}
    	public String getText(){
    		int caretPosition = jta.getDocument().getLength();
    		Element root = jta.getDocument().getDefaultRootElement();
    		String text = "1\n";
    		for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++)
    			text += i + "\n";
    		return text;
    	}
     
    	/* Mouse Listener Events */
    	public void mouseClicked(MouseEvent me) {
    		if(me.getClickCount() == 2){
    			try {
    				int caretPos = lines.getCaretPosition();
    				int lineOffset = lines.getLineOfOffset(caretPos);
    				if(lines.getText().charAt(caretPos-1) == '\n')
    					lineOffset--;
    				highlighter.addHighlight(jta.getLineStartOffset(lineOffset),
    										 jta.getLineEndOffset(lineOffset), 
    										 new MyHighlighter(Color.cyan));
    			} catch (BadLocationException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	public void mouseEntered(MouseEvent me) {}
    	public void mouseExited(MouseEvent me) {}
    	public void mousePressed(MouseEvent me) {}
    	public void mouseReleased(MouseEvent me) {}
    	public void mouseDragged(MouseEvent me) {}
    	public void mouseMoved(MouseEvent me) {}
     
    	/* Focus Listener Events for line numbers*/
    	public void focusGained(FocusEvent fe) {}
    	public void focusLost(FocusEvent fe) {
    		highlighter.removeAllHighlights();
    	}
    	public static void main(String[] args){
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                                                       public void run() {
                                                                  new MainWindow().createAndShowGUI();
                                                       }
                                               });
    	}
    }
    [/code]
    [code]
    import java.awt.Color;
    import javax.swing.text.DefaultHighlighter;
     
    public class MyHighlighter extends DefaultHighlighter.DefaultHighlightPainter {
    	public MyHighlighter(Color c) {
    		super(c);
    	}
    }

    Enjoy,

    Chris
    Last edited by Freaky Chris; October 15th, 2010 at 04:37 AM.
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

  8. #7
    Junior Member
    Join Date
    Aug 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How To: Add line numbers to your JTextArea

    Quote Originally Posted by Freaky Chris View Post
    Well, I know a few people have wanted to do things like this before. So here is my code approach to it, enjoy. There are other methods I'm sure, but I think this is the easiest.

    It makes use of the JScrollPane Row Header

    import java.awt.Color;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Element;
     
     
    public class LineNumbering extends JFrame{
    	private static JTextArea jta;
    	private static JTextArea lines;
     
    	public LineNumbering(){
    		super("Line Numbering Example");
    	}
     
    	public static void createAndShowGUI(){
    		JFrame frame = new LineNumbering();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		JScrollPane jsp = new JScrollPane();
    		jta = new JTextArea();
    		lines = new JTextArea("1");
     
    		lines.setBackground(Color.LIGHT_GRAY);
    		lines.setEditable(false);
     
    		jta.getDocument().addDocumentListener(new DocumentListener(){
    			public String getText(){
    				int caretPosition = jta.getDocument().getLength();
    				Element root = jta.getDocument().getDefaultRootElement();
    				String text = "1" + System.getProperty("line.separator");
    				for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++){
    					text += i + System.getProperty("line.separator");
    				}
    				return text;
    			}
    			@Override
    			public void changedUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void insertUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void removeUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    		});
     
    		jsp.getViewport().add(jta);
    		jsp.setRowHeaderView(lines);
    		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     
    		frame.add(jsp);
    		frame.pack();
    		frame.setSize(500,500);
    		frame.setVisible(true);
    	}
     
    	public static void main(String[] args){
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
    	}
    }

    Chris
    Thnks dis helped me a lot but could u plz provide some explanation abt dis code would of greta help.....

  9. #8
    Junior Member
    Join Date
    Oct 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How To: Add line numbers to your JTextArea

    Good code.

  10. #9
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    814
    My Mood
    Devilish
    Thanks
    7
    Thanked 99 Times in 86 Posts

    Default Re: How To: Add line numbers to your JTextArea

    I'm glad people are finding this useful, again I will develop this further upon request by members.


    Thanks Guys
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

  11. #10
    Junior Member
    Join Date
    Mar 2011
    Posts
    1
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How To: Add line numbers to your JTextArea

    Quote Originally Posted by Freaky Chris View Post
    Well, I know a few people have wanted to do things like this before. So here is my code approach to it, enjoy. There are other methods I'm sure, but I think this is the easiest.

    It makes use of the JScrollPane Row Header

    import java.awt.Color;
     
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.Element;
     
     
    public class LineNumbering extends JFrame{
    	private static JTextArea jta;
    	private static JTextArea lines;
     
    	public LineNumbering(){
    		super("Line Numbering Example");
    	}
     
    	public static void createAndShowGUI(){
    		JFrame frame = new LineNumbering();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		JScrollPane jsp = new JScrollPane();
    		jta = new JTextArea();
    		lines = new JTextArea("1");
     
    		lines.setBackground(Color.LIGHT_GRAY);
    		lines.setEditable(false);
     
    		jta.getDocument().addDocumentListener(new DocumentListener(){
    			public String getText(){
    				int caretPosition = jta.getDocument().getLength();
    				Element root = jta.getDocument().getDefaultRootElement();
    				String text = "1" + System.getProperty("line.separator");
    				for(int i = 2; i < root.getElementIndex( caretPosition ) + 2; i++){
    					text += i + System.getProperty("line.separator");
    				}
    				return text;
    			}
    			@Override
    			public void changedUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void insertUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    			@Override
    			public void removeUpdate(DocumentEvent de) {
    				lines.setText(getText());
    			}
     
    		});
     
    		jsp.getViewport().add(jta);
    		jsp.setRowHeaderView(lines);
    		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     
    		frame.add(jsp);
    		frame.pack();
    		frame.setSize(500,500);
    		frame.setVisible(true);
    	}
     
    	public static void main(String[] args){
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
    	}
    }

    Chris
    Hello! I have a doubt.
    Everytime I modify the text in the JTextArea, the "number area" updates and scrolls down to the end. I mean, if I write a character at line 67 out of 100, the "line number area" shows me 95 96 97 98 99 100... just the end and it doesn't stays at that line number (67 in this case).

    How can I fix that? I'm kind of stuck there.

    I hope you can help me.
    Thanks.

  12. #11
    Junior Member
    Join Date
    Mar 2011
    Location
    Germany
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How To: Add line numbers to your JTextArea

    hi all,

    i am new to this forum, so at first i just want so say hello to all :-)

    i have a little project implementing some own grammar language
    for some german linguists and want to have a nice little IDE
    to edit those grammars ...
    so i startet to create some basic IDE features with swing
    an netbeans.
    i used the code here and found, which seems very helpful for me,
    but i also noticed some problems ...

    1. display of linenumbers
    in some circumstances the scrolling of the editor component and the
    line header in scoll bar are not synchronized.
    which means scrolling posion is not the same and the displayed lineno
    does not represent the actual one ...
    i currently not know how to sync theese components ... :-(

    2. jtextpane and linewrap
    for syntaxhighlighing functions i need jtextpane insted of
    jtextarea.
    out of the box you can't easly turnoff linewrapping in jtextpane.
    if you use a little trick and enclose the jtextpane in a pane which
    layout is set to 'border' you can simulate no line wrap.
    the problem is, if you type out of the viewport you cant see the edit-
    cursor, which is out of the viewport ...
    maybe this also have to be synced somehow with scrolling ...

    maybe anybody has a great idea or some useful experience on this :-)

    thank you in andvance

    regards
    patrick

Similar Threads

  1. How to Change JTextArea font, font size and color
    By Flash in forum Java Swing Tutorials
    Replies: 7
    Last Post: January 14th, 2012, 09:47 PM
  2. Random numbers
    By Pooja Deshpande in forum Java SE APIs
    Replies: 8
    Last Post: June 5th, 2009, 04:36 AM
  3. Replies: 1
    Last Post: May 21st, 2009, 03:41 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM
  5. How to Read a file line by line using BufferedReader?
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: May 19th, 2008, 06:32 AM