Search code examples
javaswingjscrollpanejtextpanescrollable

Scrollable text not depending on text length


I'm creating a GUI with a sidebar which has constant width, I want to add a Scrollable text, being the text into a JTextPane, all this into a JPanel PanelList.

Problem is that it will automatically adjust to the length of the longest string so the scrollable is always showing the whole text - that's not what I'm looking for.

Having this code:

public PanelList(int size){

        text = new JTextPane();
        text.setEditable(false);
        text.setText("IwantthisStringtobeScrollable\n" +
                "ThisStringis30characterslength");
        JScrollPane scrollpane = new JScrollPane(text);
        scrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        this.add(scrollpane);

}

What method do I have to invoke so as to show only 20 chars of the JTextPane and be able to scroll?

EDIT: The width to be shown by the scrollpanel is that of the param size.


Solution

  • What method do I have to invoke so as to show only 20 chars of the JTextPane

    A JTextPane doesn't support this concept.

    If you are only displaying simple text (and don't need multiple fonts or text color) then you can use a JTextArea. Then you would do something like:

    JTextArea textArea = new JTextArea(5, 20);
    JScrollPane scrollPane = new JScrollPane(textArea);
    

    This will create a text area that contains 5 rows and 20 columns. The columns is not exact because the width of every character is different. If you want exactly 20 characters then you would need to use a monospaced font.