Search code examples
javaswingjscrollpane

Java. Swing. JScrollPane's JViewport size changed


I have a customText component in a JScrollPane. When the text is empty and there are no scrollbars, I can see all the text. But when the scrollbars become visible, some text is "hidden" behind these scrollbars. Maybe I can listen to JViewPort size changes and set preferredsize for my text component?

JComponent component = getResTextArea();
component.setPreferredSize(RES_TEXT_AREA_PREFFERED_SIZE);
JScrollPane scrollPane = new JScrollPane(component);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.getVerticalScrollBar().setUnitIncrement(UNIT_INCREMENT);
panel.add(scrollPane);

I see how size of the viewport changes when text exceeds the panel's visible area and scrollbars being shown.

EDIT. My custom component is a subclass of JEditorPane.


Solution

  • The best way to implement this would be for your custom component to implement javax.swing.Scrollable, with getScrollableTracksViewportWidth() returning true. This will lock the width of your JComponent to the width of the viewport.