Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
 }
like image 830
0xCursor Avatar asked Jan 25 '26 08:01

0xCursor


1 Answers

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.

like image 105
Reimeus Avatar answered Jan 27 '26 23:01

Reimeus