Search code examples
javaswingjscrollpane

JScrollPane doesn't show when using with JTextPane


I am trying to show a scroll bar next to my text pane but I can't find the reason why it doesn't show.

    this.setLayout(null);

    editorPane = new JTextPane();

    size = editorPane.getPreferredSize();
    editorPane.setBounds(17, 12, 533, size.height * 3);
    editorPane.setBackground(Color.BLACK);
    editorPane.setForeground(Color.WHITE);
    //editorPane.setEditable(false);
    console = editorPane.getStyledDocument();

    scrollConsole = new JScrollPane(editorPane);
    scrollConsole.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    this.add(editorPane);
    this.add(scrollConsole);

Solution

  • Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

    See Why is it frowned upon to use a null layout in SWING? for more details...

    You have two basic mistakes...

    1. You've decided to use a null layout, but neglected to set the size of the JScrollPane
    2. You set the JTextPane as the view for the JScrollPane but then add it to the container, along with the JScrollPane. A component can only belong to a single container, by adding it a second time, you've removed it from the JScrollPane

    See How to Use Scroll Panes for more details