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

北战南征 提交于 2019-12-10 02:45:11

问题


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!


回答1:


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()
        );  
    }



回答2:


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);
  }
}       



回答3:


Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)


来源:https://stackoverflow.com/questions/11745595/how-to-create-a-rectangle-object-in-java-using-g-fillrect-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!