Java, how to drawing rectangle variables on my screen

给你一囗甜甜゛ 提交于 2019-12-11 23:59:45

问题


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?


回答1:


This seams to be double values:

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

The methods return doubles. See here API

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


来源:https://stackoverflow.com/questions/14148353/java-how-to-drawing-rectangle-variables-on-my-screen

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