5

How can I restrict JScrollPanel view width? I do not want horizontal scroll to happen in any case. I tried to supply own JViewport but that does not help a lot.

private static class WidthRestrictingViewport extends JViewport {
        private Container contents;

        public WidthRestrictingViewport(final Container cnts) {
            contents = cnts;
        }

        @Override
        public Dimension getPreferredSize() {
            if (getParent() instanceof JScrollPane) {
                JScrollPane sp = (JScrollPane) getParent();
                return new Dimension(sp.getWidth(), contents.getHeight());
            }
            return super.getPreferredSize();
        }

        @Override
        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    }

And code that create JScrollPane

Container fpdp = ....

    JScrollPane sp = new JScrollPane();
    sp.setViewport(new WidthRestrictingViewport(fpdp));
    sp.setViewportView(fpdp);

contents instance that I supply takes its maximum width, however I want its width to be no more than JScrollPane width so horizontal scrolling wont happen. What am I doing wrong?

michael nesterenko
  • 14,222
  • 25
  • 114
  • 182
  • 1
    I do not understand the question. What should happen with the contents of the `JScrollPane` when it is wider then the actual size of the `JScrollPane`. Simply cut off ? In that case you might consider just making the scroll bar invisible (`JScrollPane#getHorizontalScrollBar#setVisible( false )`); – Robin Nov 13 '12 at 22:45
  • @Robin, Not cut off. Shrink view width to scroll pane width. Just imagine panel with border layout and contents placed into center. But in this case only contents' width is restricted with panel's width and contents' height may grow as it needs (with scroll bar adding). – michael nesterenko Nov 13 '12 at 22:56
  • 1
    I don't think it's the responsibility of the `JViewPort` to place restrictions on it's view as to the width it can achieve, this is more about the view itself. Take a look at the [`Scrollabe`](http://docs.oracle.com/javase/7/docs/api/javax/swing/Scrollable.html) interface, in particular [`Scrollable#getScrollableTracksViewportWidth`](http://docs.oracle.com/javase/7/docs/api/javax/swing/Scrollable.html#getScrollableTracksViewportWidth%28%29) – MadProgrammer Nov 14 '12 at 00:38

1 Answers1

2

Sorry for my poor explanations. I found a way to do that. Thanks to JScrollpane needs to shrink its width.

One more problem I faced is wrong layout manager in ScrollablePanel. That was FlowLayout that screwed all things up. I did not understand it at once and thought that problem is with Scrollable interface usage.

So I just took ScrollablePanel and set its layout manager to BorderLayout and that is all fine now!

Community
  • 1
  • 1
michael nesterenko
  • 14,222
  • 25
  • 114
  • 182