Search code examples
javagraphicscenter

How to dynamically center a Graphic


Although in this example, the X-Y values are hard-coded, lets assume the user entered the values dynamically and clicked a button to view the results on the screen.

It wouldn't make sense to calculate the frame based on the largest size as the Frame would be too large for the monitor.

What is required to take the X-Y values entered (not matter how large or small) and have the image appear centered within the frame?

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Path2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ZoomToXY extends JPanel 
{
    int x = 0;
    public void paint(Graphics g) 
    {
        //Can't see this. 
        int[] xs2 = {5308,  5306, 4143, 4143, 4120, 4119, 4118, 4117, 4116, 4114, 4112};
        int[] ys2 = {4474,  5329, 5306, 5171, 5171, 5173, 5175, 5177, 5179, 5181, 5182};

        BasicStroke traceStroke = new BasicStroke (1);  //Line thickness
        Graphics2D gc = (Graphics2D) g.create();

        gc.setColor(Color.RED);
        gc.drawPolyline(xs2, ys2, 11);
        gc.setStroke(traceStroke);
        x++;
    }

    public static void main(String[] args) 
    {
        JFrame frame = new JFrame();
        frame.add(new ZoomToXY());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(20,20, 250,250);
        frame.setVisible(true);
    }
}

Solution

  • The reason we can't see the polygon or whatever you're making, is because it's outside the frame's bounds. Let's take a look.

    frame.setBounds(20,20, 250,250);
    

    This line indicates we will only see what's inside these bounds, though everything outside will also be drawn but not shown. Try drawing a rectangle inside the bounds and see.

    g.fillRect(20, 20, 100, 100);
    

    You will see a rectangle. But how can I solve this issue? Since having a frame being 5000px by 5000px isn't going to work on most monitors, either you work with smaller resolutions and therefore smaller coordinates, or you implement a camera. Having a camera you can have as big world as you want and being able to move around in it. But if your frame can only show 100 pixels and your polygon is 1000px, we will only see 10% of it, this problem can easily be solved with zooming. Here is a topic how to implement a gamecamera. With the gameCamera you can simply calculate the center of your image, then translate it, quite simple. If you need assistance just ask.

    A frame that is 250x250 is quite small, consider it being a little bigger. Also why set the coordinates as (20, 20)? If you want to center the JFrame to the current monitor just call:

    frame.setLocationRelativeTo(null);