0xCursor
0xCursor

Reputation: 2268

How can I center a drawn object in a JFrame?

I am making a program that draws a circle on a JFrame. I want to start the program with the circle in the center of the screen so that even if the size of the JFrame window is changed, it is still centered. How would I do it? I have tried different things but haven't found anything that works yet. The code is down below:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageFrame extends JFrame {
    private static final long serialVersionUID = 1L;

    int width = 40;
    int height = 40;
    int x = 160;
    int y = 70;

    JPanel panel = new JPanel() {
        private static final long serialVersionUID = 1L;
        public void paintComponent(Graphics g) {
            super.paintComponents(g);
            g.drawOval(x, y, width, height);
            }
    };

    public ImageFrame() {
        add(panel);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);
        setVisible(true);
    }
 }

Upvotes: 3

Views: 2190

Answers (1)

Reimeus
Reimeus

Reputation: 159754

This is a simple math problem. Divide the difference of the container width and the circle width by 2 to locate the x co-ordinate for drawOval. Do the same for the height for the y co-ordinate.

Upvotes: 3

Related Questions