How to add scrollbar to a JPanel with Graphics
I have a JInternalFrame. Inside this frame I have a JPanel which is a drawing panel.
It implements the paint() method and draws something within the panel.
I want to add a scrollbar for this JPanel so that I can scroll down and see different parts of what I draw. I use the following code within a method in JInternalFrame:
jp = new DrawingPanel(); // DrawingPanel is a subclass of JPanel which implements paint();
JScrollPane scroller = new JScrollPane(jp);
scroller.setVerticalScrollBarPolicy(ScrollPaneCons tants.VERTICAL_SCROLLBAR_ALWAYS);
add(scroller);
add(jp);
The program can compile. and I can see the graphics inside the DrawingPanel.
But the problem is that the scrollbar doesn't even appear.
How can I fix this problem with the least modification to the whole structure of the program?
Re: How to add scrollbar to a JPanel with Graphics
First, you should override the paintComponent method rather than the paint method (if that is truly what you've done). Second, set the preferred size of the JPanel you've added to the JScrollPane (before the JScrollPane is visible - if added after then call revalidate on the added JPanel) - this should let the JScrollPane know the size of the component it is trying to display.