簡體   English   中英

如何從我的主類在我的畫布上繪制一個矩形?

[英]How can I draw a rectangle to my canvas from my main class?

我知道我可以使用緩沖策略(在循環內)來做到這一點,但是有沒有辦法在沒有緩沖策略(在循環內)的情況下做到這一點?

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);
    }
}

我不記得 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();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM