Java Swing JPanel。如何绘制形状?
我已经实现了一个类 DrawingPane extends JPanel
来绘制一些形状。我在内部为每种类型的形状创建了一个单独的方法,例如对应的圆形:
public void paintCircles(Graphics g) {
super.paint(g);
但是我无法通过对类 DrawingPane
的引用从另一个类调用它。这怎么能做到呢?如果这种方式不可能,我如何调用单独的方法来绘制每种类型的形状,因为不同形状的代码要求不同?
此外,类JPanel
中的方法scrollRectToVisible 不适用于对象RoundRectangle2D.Double
。如何才能让这些形状也可见呢?
I have implemented a class DrawingPane extends JPanel
to draw some shapes. I have created inside an individual method for each type of shape, for example to circles corresponds :
public void paintCircles(Graphics g) {
super.paint(g);
However I am not able to invoke this from another class through a reference to class DrawingPane
. How can this be done? If it is not possible this way, how can I invoke an individual method to draw each type of shape, since the code requirements are different with different shapes?
Moreover, the method scrollRectToVisible from class JPanel
does not apply to objects RoundRectangle2D.Double
. How can make these shapes also visible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在
DrawingPane
中实现paintComponent(Graphics g)
,并且可以使用draw(Shape s)
绘制任何形状:You need to implement
paintComponent(Graphics g)
in yourDrawingPane
and you can usedraw(Shape s)
to draw any shape:您可以将
Graphics
转换为Graphics2D
并使用public void draw(Shape s)
方法传递所有Shape
你有。对于任何Shape
,您可以使用public Rectangle getBounds()
并将Rectangle
传递给scrollRectToVisible。You can cast your
Graphics
toGraphics2D
and usepublic void draw(Shape s)
method passing all theShape
s you have. For anyShape
you can usepublic Rectangle getBounds()
and pass theRectangle
to the scrollRectToVisible.