简体   繁体   English

如何移动JPanel的所有内容?

[英]How to move all the content of a JPanel?

I have a class that inherits from JPanel . 我有一个继承自JPanel的类。 It is called DrawingPanel and in this class I draw lines and shapes using Graphics2D and I use the position of user's mouse to do some operations on these shapes. 它称为DrawingPanel ,在此类中,我使用Graphics2D绘制线条和形状,并使用用户鼠标的位置对这些形状进行一些操作。

The drawings in the panel can take a lot of space on screen (for instance I may draw lines from (-200, -300) to (2000, 1000)), so actually I only see a part of the drawings. 面板中的绘图可能会在屏幕上占用大量空间(例如,我可能会画出从(-200,-300)到(2000,1000)的线),因此实际上我只看到了一部分绘图。 That's why I would like to be able to move all things drawn in my panel with scrolling. 这就是为什么我希望能够通过滚动移动面板中绘制的所有内容。

Is there a simple and elegant solution to do this, and that would not require too much changes in my code? 是否有一个简单而优雅的解决方案来执行此操作,而这不需要对我的代码进行太多更改?

EDIT: Actually my problem is that I don't know an elegant way to have scrolling working in a JPanel with shapes drawn with Graphics2D . 编辑:实际上,我的问题是我不知道一种优雅的方式来使在Graphics2D绘制的形状的JPanel进行滚动。 I tried to add my JPanel to a JScrollPane but it did not worked. 我试图将我的JPanel添加到JScrollPane但是没有用。 Practically, what should I have to add to my code? 实际上,我应该在代码中添加什么?

Put your drawing code in a separate method, called (for example) draw which takes 1 argument, a Graphics object. 将绘图代码放在一个单独的方法中,该方法称为(例如) draw ,该方法带有1个参数Graphics对象。
In the paintComponent method you translate() the Graphics object according tonwhoch area of the drawing should be shown and then pass it into your draw method. paintComponent方法中,应显示根据图形的tonwhoch区域translate() Graphics对象,然后将其传递到draw方法中。

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

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