Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 801
imulsion Avatar asked Jul 31 '12 17:07

imulsion


People also ask

How do you create a rectangle object in Java?

In Java, to draw a rectangle (outlines) onto the current graphics context, we can use the following methods provided by the Graphics/Graphics2D class: drawRect(int x, int y, int width, int height) draw3DRect(int x, int y, int width, int height, boolean raised) draw(Rectangle2D)

What is G fillRect in Java?

Commonly used methods of Graphics class: public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height.

What is the use of DrawArc () method in Java?

This method is used to draw an arc representing a portion of an ellipse specified by a pair of coordinates, a width, and a height. Syntax: public void DrawArc (System.

How do you fill a rectangle in Java?

Draw rectangles, use the drawRect() method. To fill rectangles, use the fillRect() method : Shape « 2D Graphics GUI « Java.


2 Answers

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()
        );  
    }
like image 120
Zac Avatar answered Oct 13 '22 00:10

Zac


You may try like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {
    g.drawRect (x, y, width, height);    //can use either of the two//
    g.fillRect (x, y, width, height);
    g.setColor(color);
  }

}

where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue

if you want to use rectangle object you could do it like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {    
    Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
    g.setColor(color);
  }
}       
like image 22
heretolearn Avatar answered Oct 13 '22 00:10

heretolearn