Search code examples
javaswingjpaneljscrollpanepaintcomponent

Scrollable JPanel based on it's paintComponent


I am using java-2d to visualize my application. I've created the panel with extending of JPanel to draw a simple rectangle. I've named this MyPanel.

So, the width and height of panel dynamically changed by rectangle definition. I use JScrollPane to add scroll ability to my panel like below:

JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

I use below code to add my panel to window:

JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1,1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setResizable(false);

MyPanel panel = new MyPanel();

JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.add(scrollPane);
frame.setVisible(true);

Now, in paintComponents of MyPanel, I want to paint the rectangle with the width and height that are more than container (frame) width and height. But the scroll is not working.

What is wrong? Could any one help me?

Thanks in advance :)


Solution

  • The scroll pane uses the components preferred size to determine how big it should be and provides scrolling when the components size is larger then size of the scroll pane...

    Try overriding the getPreferredSize method of the custom component and return the size you want

    If the size of MyPanel changes over the runtime of your program, use a reference to a Dimension (returned by getPreferredSize) and call revalidate when you change it