如何从我的主类在画布上绘制一个矩形?

Posted

技术标签:

【中文标题】如何从我的主类在画布上绘制一个矩形?【英文标题】:How can I draw a rectangle to my canvas from my main class? 【发布时间】:2021-01-31 10:40:18 【问题描述】:

我知道我可以使用缓冲策略(在循环内)来做到这一点,但是有没有办法在没有缓冲策略(在循环内)的情况下做到这一点?

import javax.swing.JFrame;

public class JavaApplication28 

    public static void main(String[] args) 
        JFrame f = new JFrame("Title");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MyCanvas mycanvas = new MyCanvas();
        f.add(mycanvas);
        f.setSize(400,250);
        f.setVisible(true); 

        //I would like to create the rectangle on the canvas here, which is possible with bufferstrategy

    

import java.awt.Canvas;
import java.awt.Graphics;

public class MyCanvas extends Canvas
    public MyCanvas ()
        
    

    //Do I call paint() in my main class, something like mycanvas.paint().drawRect(100, 100, 100, 100)? Is there such syntax?
 
    public void paint(Graphics g) 
        super.paint(g);
        g.drawRect(100, 100, 100, 100);
    

【问题讨论】:

【参考方案1】:

我不记得 AWT 画布是否有 repaint()... 20 年没用过了 :) 在画布中保存一组“渲染”对象,然后根据需要添加/删除和重新绘制。

public class MyCanvas extends Canvas
    private final List<Shape> shapes;
    public MyCanvas ()
        shapes = new ArrayList();
    

    public List<Shape> renderedShapes() 
       return shapes;
    
    
    public void paint(Graphics g) 
        super.paint(g);
        // the shapes are created in the main class but once you add them to the renderedShapes() array of this canvas, you have access to them and the graphics context at this point and can render them.
        for (Shape s : shapes)                
           renderShape(g, s);
        
    


private void renderShape(Graphics g, Shape shape) 
   if (Shape instanceof Rectangle) 
          Rectangle rect = (Rectangle)shape;
          g.drawRect(rect.x, rect.y, rect.width, rect.height);
    else if (Shape instanceof Circle) 
       Circle circle = (Circle)shape;
       g.drawCircle(circle.x, circle.y, circle.radius);
   



public static void main(String[] args) 
   MyCanvas canvas = new MyCanvas();
   canvas.renderedShapes().add(new Rectangle(0,0,10,10));
   canvas.repaint();


【讨论】:

你能扩展// render your shape我想不出任何东西可以放在那里。由于 Rectangle 是在主类中创建的。是g.s吗? 详细说明。不要把添加的东西当作“工作”,因为我没有测试它。但它的要点是确定形状的类型并使用图形参数进行绘制。 并且 RenderShape(Graphics, Shape) 方法应该在 MyCanvas 类中......但对于我来说,我无法在这个垃圾网页视图中编辑它而不破坏整个缩进:p 我应该用什么替换 varfor (var s : shapes) (Shapes s : shapes)吗?

以上是关于如何从我的主类在画布上绘制一个矩形?的主要内容,如果未能解决你的问题,请参考以下文章

通过按钮将矩形绘制到画布上

在画布上用鼠标绘制矩形与鼠标坐标不同步

如何在画布内的文本周围绘制矩形

HTML5 Canvas - 如何在画布中的图像上绘制矩形

Javascript画布 - 矩形中的相交圆孔或如何合并多个圆弧路径

如何通过按下和拖动在 Qt Quick/QML 画布中绘制一个矩形