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?

有帮助吗?

解决方案

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

其他提示

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

scrollPane.getViewport().setViewPosition( new Point(x1, y1) );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top