简体   繁体   English

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

[英]How can I center a drawn object in a JFrame?

I am making a program that draws a circle on a JFrame .我正在制作一个在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.我想以屏幕中心的圆圈启动程序,这样即使JFrame窗口的大小发生变化,它仍然居中。 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);
    }
 }

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 .将容器宽度和圆形width除以 2 以定位drawOval的 x 坐标。 Do the same for the height for the y co-ordinate.对 y 坐标的height执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM