Search code examples
javaswingresizejscrollpanejeditorpane

Force JEditorPane within JScrollPane to shrink + re-wrap


Having an issue with a JScrollPane expanding its child JEditorPane just fine but forcing horizontal scroll bars when resizing it down again (instead of forcing the JEditorPane to recalculate wrapping).

The basic flow of code is as follows:

JFrame f = new JFrame();
JEditorPane jep = new JEditorPane();
JScrollPane jsp = new JScrollPane(jep);
f.add(jsp);

Solution

  • It's a hack, but the best way I could find (without using ugly ScrollPaneManagers) was to implement a ComponentListener on the JScrollPane to resize the child component whenever it was resized.

    jsp.addComponentListener(new ComponentListener() {
        @Override
        public void componentShown(ComponentEvent e) {}
    
        @Override
        public void componentResized(ComponentEvent e) {
            Dimension jspSize = ((JScrollPane)e.getComponent()).getViewport().getSize();
            jep.setBounds(0, 0, jspSize.width, jspSize.height);
        }
    
        @Override
        public void componentMoved(ComponentEvent e) {}
    
        @Override
        public void componentHidden(ComponentEvent e) {}
    });