在JScrollPane中滚动JComponent [英] Scrolling JComponent in JScrollPane

查看:84
本文介绍了在JScrollPane中滚动JComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个很大的JComponent:

Say, I have a big JComponent:

Dimension componentSize = new Dimension(5000,5000);

还有一个较小的JScrollPane:

And a smaller JScrollPane:

Dimension scrollPaneSize = new Dimension(500,500);

我想在JScrollPane中显示我的JComponent的一部分,如下图所示:

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

白色矩形是我的JScrollPane,当前显示JComponent的一部分,从(x1,y1)(x2,y2).

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

所以,我尝试了什么:

我创建了一个新的JComponent:

I have created a new JComponent:

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

并将其作为JScrollPane中的视口视图放置:

And placed it as a viewport view in JScrollPane:

JScrollPane scrollPane = new JScrollPane();

scrollPane.setViewportView(component);

然后我将JScrollPane附加到JFrame:

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)

怎么了?

推荐答案

setBounds用于确定组件在其父容器中的位置和大小.这不是您想要的.除非您使用绝对布局,否则永远不要使用此方法.

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.

相反,尝试

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

相反...

签出 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆