Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am messing around with the Graphics class and have noticed that the location and size of the rectangles I draw do not add up.

        // Game.HEIGHT = 800
        // Game.WIDTH = 800
        g.drawRect(Game.WIDTH/2 -50, Game.HEIGHT/2 -50, 100, 100);

This should draw a rectangle in the enter of the screen just using math, but it is quite offset. I feel like I am missing something, because math wise this should work, and I could use some explanation.

question from:https://stackoverflow.com/questions/65877132/java-rectangle-location-is-wrong

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
336 views
Welcome To Ask or Share your Answers For Others

1 Answer

Not really an answer, just debugging help.

How do you know the actual size of the panel is 800?

How do you know your x/y values are correct?

Don't use math expressions for parameters. Instead your code should be something like:

int size = 100;
int x = (Game.WIDTH - size) / 2;
int y = (Game.HEIGHT - size) / 2;
System.out.println("Panel size: " + getSize());
System.out.println(x + " : " + y);
g.drawRect(x, y, size, size);

This allows you to display the value of your parameters to make sure they are what you expect them to be.

Instead of hardcoding the width/height of the panel you should use the actual size of the panel as determined by the getSize() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...