比如说,我有一个很大的 JComponent:
Dimension componentSize = new Dimension(5000,5000);
还有一个更小的 JScrollPane:
Dimension scrollPaneSize = new Dimension(500,500);
我想在 JScrollPane 中显示我的 JComponent 的一部分,如下图所示:
白色矩形是我的 JScrollPane,它当前显示从 (x1,y1) 到 (x2,y2) 的部分 JComponent。
那么,我尝试了什么:
我创建了一个新的 JComponent:
JComponent component = new JComponent(){
protected void paintComponent(Graphics g)
{
// Here I draw a background
}
};
并将其作为视口(viewport) View 放置在 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));
相反...
关于java - 在 JScrollPane 中滚动 JComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399315/