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

Categories

0 votes
322 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...