如何在 Java 中使用 g.fillRect 方法创建一个 Rectangle 对象 [英] How to create a Rectangle object in Java using g.fillRect method

查看:15

问题描述

我需要创建一个矩形对象,然后使用paint() 将其绘制到小程序中.我试过了

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

然后尝试使用

g.draw(r);

没用.有没有办法在java中做到这一点?我已经在谷歌的一英寸范围内搜索了答案,但我一直无法找到答案.请帮忙!

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!

推荐答案

试试这个:

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

// 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()
        );  
    }
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆