Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

draw - Java rectangle location is wrong

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...