Search code examples
javajtextarealine-numbersrights

Java how to display line number on the right side of text components


I want to display line numbers in a text component. I found this link https://tips4java.wordpress.com/2009/05/23/text-component-line-number/ And it worked. But I want to display line number on the right side of textarea. How can I do it. Thank!


Solution

  • TextLineNumber is a Swing component. How do you display multiple components in a scroll pane? You add the components to a panel and then add the panel to the viewport of the scroll pane. One way might be to use a panel with a BorderLayout:

    JPanel panel = new JPanel( new BorderLayout() );
    panel.add(textArea, BorderLayout.CENTER);
    TextLineNumber lineNumber = new TextLineNumber(textArea, 3);
    panel.add(lineNumber, BorderLayout.EAST);
    JScrollPane scrollPane = new JScrollPane( panel );
    

    Or you could use the existing code and change the orientation of the scroll pane:

    scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    

    The line number will be on the right, but the scrollbar will now be on the left.