Java Swing JPanel。如何绘制形状?

发布于 2024-12-11 07:21:24 字数 411 浏览 0 评论 0原文

我已经实现了一个类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

廻憶裏菂餘溫 2024-12-18 07:21:24

您需要在 DrawingPane 中实现 paintComponent(Graphics g),并且可以使用 draw(Shape s) 绘制任何形状:

public void paintComponent(Graphics g) {
        super.paintComponent(g); 
        Graphics2D g2 = (Graphics2D)g;    
        g2.draw(yourShape);
}

You need to implement paintComponent(Graphics g) in your DrawingPane and you can use draw(Shape s) to draw any shape:

public void paintComponent(Graphics g) {
        super.paintComponent(g); 
        Graphics2D g2 = (Graphics2D)g;    
        g2.draw(yourShape);
}
薄暮涼年 2024-12-18 07:21:24

您可以将 Graphics 转换为 Graphics2D 并使用 public void draw(Shape s) 方法传递所有 Shape你有。对于任何Shape,您可以使用public Rectangle getBounds() 并将Rectangle 传递给scrollRectToVisible。

You can cast your Graphics to Graphics2D and use public void draw(Shape s) method passing all the Shapes you have. For any Shape you can use public Rectangle getBounds() and pass the Rectangle to the scrollRectToVisible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文