How to make a JPanel scrollable? I implemented the scrollable interface yet when adding it to the containing panel with
tabbedPane.add("Editor", new JScrollPane(storeyEditor = new MNScrollablePanel()));
nothing works
Code:
public class MNScrollablePanel extends JPanel implements Scrollable {
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 10;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 10;
}
}
JPanel doesn't implements Scrollable. It is better to use JXPanel from SwingX, which implements Scrollable and has lot more features.
You have to use a
JScrollPane
. And then call thesetViewportview(Component)
;You don't have to implement scrollable, JPanel is allready scrollable
As mentioned in all the other posting there is no reason to implement the Scrollable interface yourself. However, if you are just playing around, then the basic code posted looks reasonable. However you did not post your demo program showing how you use this code. In the future, post a SSCCE with your question. If you don't know what a SSCCE is then search the web.
Once possible problem is that scrollbars appear automatically when the "preferred size" of the component added to the viewport of the scrollpane is greater than the size of the scrollpane.
So if you are doing custom painting on the panel, you are responsible for setting the preferred size of the panel as it changes. If you are using a panel with components and a layout manager then you don't have to worry about this. But if you are using components with a null layout manager you will also have problems.
That is why we need a SSCCE because we don't know the context of how you are using the panel.
It worked with me like this....
I have a new solution for you.
I think you have to use this code:
This was a solution for me. I hope for you to!