Edward Ruchevits
Edward Ruchevits

Reputation: 6696

Scrolling JComponent in JScrollPane

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?

Upvotes: 1

Views: 1389

Answers (2)

camickr
camickr

Reputation: 324108

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

scrollPane.getViewport().setViewPosition( new Point(x1, y1) );

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347194

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

Upvotes: 4

Related Questions