How to create a Rectangle object in Java using g.fillRect method

imulsion picture imulsion · Jul 31, 2012 · Viewed 107.3k times · Source

I need to create a rectangle object and then paint it to the applet using paint(). I tried

Rectangle r = new Rectangle(arg,arg1,arg2,arg3);

Then tried to paint it to the applet using

g.draw(r);

It didn't work. Is there a way to do this in java? I have scoured google to within an inch of its life for an answer, but I haven't been able to find an answer. Please help!

Answer

Zac picture Zac · Jul 31, 2012

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }