Skip to content
Advertisement

How to transform the coordinates of a JPanel to the coordinates of a graph

I’m not sure if this is a math or a programming question, but i don’t know how i can transform the coordinates of a JPanel to the coordinates of a graph. If i have a JPanel with 800×1000 size and the graph has the sizes -2 to 2(x) and -2 to 2(y) and i am drawing something on ths graph(i don’t need any help with that), and i want to have a new graph by clicking on the jpanel in the corresponding corners(i don’t need help with the code to get the coordinates), how can i get the x and y values of these corners. e.g. i click on P(400(width)|600(height)) on the JPanel and on P(600|800), how can i get the values of x and y these corners would have?(Since its a JPanel, the top left corner is P(0|0) and the bottom right corner P(800|1000). There is no code i have to provide since its rather a math question than a coding question, but i was not sure if people on mathoverflow would know how jpanels work.

Advertisement

Answer

Let’s work through a simple example.

I’m not sure what -2 to 2(x) means. Let’s assume a linear graph going from -2 to 2 on the X-axis and a drawing JPanel of 1000 x 800 pixels. If your graph uses a logarithmic scale then the math will be much more complicated.

Your X pixel count goes from 0 to 1000. So 0 represents -2 and 1000 represents 2.

The formula to convert values to pixels is:

pixels = (value + 2.0) X 1000 / 4.0  

or, in more general terms

pixels = (value - minimum value) X (total pixels) / (maximum value - minimum value)

The equation is the same for the Y direction unless you want to invert the Y value. Cartesian graphs have the Y axis going upward in a positive direction while a drawing JPanel has Y values increasing going downward.

If you do want to invert the Y axis, the formula is

pixels = total pixels - calculated pixels (the formula already given)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement