I'm trying to draw objects onto a canvas from an array, but the thing is, I have no clue how to? This must include the position and sizes of the shapes, and there will be more than one type of shape. The code I've got so far(It's inefficient/bad though)

public class MCanvas extends Canvas {
    private Object[] world = {};

    public void paint(Graphics g){  
        try{  
           // How to paint all the shapes from world here?
        } catch (NullPointerException e) {  
              System.out.println(e.toString());  
        }  
      } 

}

Any ideas? Thanks.

有帮助吗?

解决方案

If your using objects that extend from java.awt.Shape, you can translate and draw them by using a Graphics2D context

Since (some whe around Java 1.3/4), the paint engine is guaranteed to use Graphics2D instance.

public void paint(Graphics g){  
    super.paint(g);
    Graphics2D g2d = (Graphics2D)g;
    for (Object o : world) {
        if (o instanceof Shape) {
            Shape shape = (Shape)o;
            //if the shape isn't created with 
            // a location, you can translate them
            shape.translate(...,...);
            g2d.setColor(....);
            g2d.draw(shape);
            //g2d.fill(...);
        }
    }
} 

You might like to take a look at 2D Graphics for more details.

Also, use a JPanel instead of Canvas and then override its paintComponent method

Have a look at Custom Painting for more details

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top