Question

Say, I have a big JComponent:

Dimension componentSize = new Dimension(5000,5000);

And a smaller JScrollPane:

Dimension scrollPaneSize = new Dimension(500,500);

I want to display part of my JComponent in JScrollPane, like on the picture below:

JComponent inside JScrollPane

White rectangle is my JScrollPane, which currently displays part of JComponent from (x1,y1) to (x2,y2).


So, what have I tried:

I have created a new JComponent:

JComponent component = new JComponent(){
    protected void paintComponent(Graphics g)
    {
        // Here I draw a background
    } 
};

And placed it as a viewport view in JScrollPane:

JScrollPane scrollPane = new JScrollPane();

scrollPane.setViewportView(component);

Then I attached JScrollPane to a JFrame:

JFrame frame = new JFrame();

frame.setLayout(new BorderLayout());

frame.add(scrollPane, BorderLayout.CENTER);

frame.pack();
frame.setVisible(true);

And I try to change visible area with:

scrollpane.getViewport().setBounds(x1,y1,500,500)

What's wrong?

Was it helpful?

Solution

setBounds is used to determine the location and size of a component within it's parent container. This isn't what you want to do. Unless you are using an absolute layout, you should never use this method.

Instead, try

component.scrollRectToVisible(new Rectangle(x1, y1, 500, 500));

Instead...

Check out JComponent#scrollRectToVisible

OTHER TIPS

This code will always cause the viewport to scroll regardless of the size of the viewport.

scrollPane.getViewport().setViewPosition( new Point(x1, y1) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top