问题描述
我知道我可以使用缓冲策略(在循环内)做到这一点,但是有没有办法不用缓冲策略(在循环内)吗?
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)? Is there such Syntax?
public void paint(Graphics g) {
super.paint(g);
g.drawRect(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,10,10));
canvas.repaint();
}