Scrolling JComponent in JScrollPane

非 Y 不嫁゛ 提交于 2019-12-11 08:28:10

问题


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:

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?


回答1:


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




回答2:


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

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


来源:https://stackoverflow.com/questions/15399315/scrolling-jcomponent-in-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!