java 绘制长方形_Java,如何在我的屏幕上绘制矩形变量

本文介绍了在Java游戏中遇到的绘制矩形错误,问题在于使用了浮点数传递给需要浮点类型参数的方法fillRect。通过将浮点数值强制转换为float类型,成功解决了编译错误,从而能够在屏幕上正确地绘制移动和静止的矩形。
摘要由CSDN通过智能技术生成

I have coded a simple Java game where there are two rectangles on the screen, one of the rectangles moves and the other stays still, the moving Rectangle moves with keyboard arrow input and can move either up, down, left or right. The problem I am having is drawing my rectangles on the screen, I have my variables set up as shown:

float buckyPositionX = 0;

float buckyPositionY = 0;

float shiftX = buckyPositionX + 320;//keeps user in the middle of the screem

float shiftY = buckyPositionY + 160;//the numbers are half of the screen size

//my two rectangles are shown under here

Float rectOne = new Rectangle2D.Float(shiftX, shiftY,90,90);

Float rectTwo = new Rectangle2D.Float(500 + buckyPositionX, 330 + buckyPositionY, 210, 150);

and under my render method (which holds all the stuff I want drawn onto the screen) I have told Java to draw my two rectangles:

public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{

//draws the two rectangles on the screen

g.fillRect(rectOne.getX(), rectOne.getY(), rectOne.getWidth(), rectOne.getHeight());

g.fillRect(rectTwo.getX(), rectTwo.getY(), rectTwo.getWidth(), rectTwo.getHeight());

}

But I am getting the following error under fillRect:

This method fillRect(float,float,float,float) in the type graphics is

not applicable for the arguments (double,double,double,double)

This is confusing me as from what I understand it is saying the information provided in fillRect should be floats which everything is, so why does it keep giving me this error?

解决方案

This seams to be double values:

rectOne.getX(), rectOne.getY(), rectOne.getWidth(), rectOne.getHeight()

Because you set float values, simply use this:

g.fillRect((float)rectOne.getX(), (float)rectOne.getY(), (float)rectOne.getWidth(), (float)rectOne.getHeight());

g.fillRect((float)rectTwo.getX(), (float)rectTwo.getY(), (float)rectTwo.getWidth(), (float)rectTwo.getHeight());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值