Search code examples
javaswinggeometrygraphics2d

How to draw a rectangle in Java?


I am working on an application that needs to draw shapes (rectangle etc) by searching an array like:

while(array!=null)
{
    if(array.equals("x"))
    then 
    drawRect(100,100,50,20);
}

Every rectangle must be drawn on a single Frame and with different coordinates.


Solution

  • There is an error in your code. The word then doesn't exist in Java.

    while(array!=null) {
        if(array.equals("x")) {
             drawRect(100,100,50,20);
        }
    }
    

    There are so many example in Google. The best of all is Drawing Geometric Primitives by Oracle Tutorials.

    public void paint (Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        if (yourCondition) {
            g2.draw(new Rectangle2D.Double(x, y, rectwidth, rectheight));
        }
    }
    

    enter image description here