如何在 JFrame 中将绘制的对象居中?

How can I center a drawn object in a JFrame?

我正在制作一个在 JFrame 上画圆的程序。我想以屏幕中央的圆圈启动程序,这样即使 JFrame window 的大小发生变化,它仍然居中。我该怎么做?我尝试过不同的方法,但还没有找到任何有效的方法。代码如下:

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);
    }
 }

这是一道简单的数学题。将容器宽度与圆 width 的差值除以 2 以定位 drawOval 的 x 坐标。对 y 坐标的 height 执行相同的操作。