简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM