繁体   English   中英

在JScrollPane中滚动JComponent

[英]Scrolling JComponent in JScrollPane

说,我有一个很大的JComponent:

Dimension componentSize = new Dimension(5000,5000);

还有一个较小的JScrollPane:

Dimension scrollPaneSize = new Dimension(500,500);

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

JScrollPane中的JComponent

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


因此,我尝试了什么:

我创建了一个新的JComponent:

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

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

JScrollPane scrollPane = new JScrollPane();

scrollPane.setViewportView(component);

然后我将JScrollPane附加到JFrame:

JFrame frame = new JFrame();

frame.setLayout(new BorderLayout());

frame.add(scrollPane, BorderLayout.CENTER);

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

我尝试使用以下方法更改可见区域:

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

怎么了?

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

相反,尝试

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

代替...

查看JComponent#scrollRectToVisible

不管视口的大小如何,此代码将始终导致视口滚动。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM