Search code examples
javaswingjtextarearowheader

Java code to display lines number in jtextarea


I trying to write java code to pop up text area and if i add 9000 lines in jtextarea at right it display 9000 lines and vertical line.

Is there anyway that i can do it?? enter image description here

Is there anyway that i can add line number like in pics..

Please help me!! Thanks!!

Here is my code:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.text.DefaultCaret;


public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        final JFrame frame = new JFrame("Test");
        JPanel panel = new JPanel();
        panel.setLayout((LayoutManager) new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(true);
        final JTextArea textArea = new JTextArea(20, 30);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(true);
        textArea.setFont(Font.getFont(Font.SANS_SERIF));
        JScrollPane scroller = new JScrollPane(textArea);
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);



        JPanel inputpanel = new JPanel();
        inputpanel.setLayout(new FlowLayout());

        JButton button = new JButton("Enter");
        DefaultCaret caret = (DefaultCaret) textArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        panel.add(scroller);

        inputpanel.add(button);
        panel.add(inputpanel);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        frame.setResizable(false);


        button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            frame.dispose();
        }});
        frame.setSize(500, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   


    }

}

Please help me!! Thanks!!


Solution

  • See Text Component Line Number for a component that can be used as a row header of the scrollpane that contains your text area.