在 Java 中绘制圆圈

Drawing circles in Java

我在创建圆时遇到问题,每当我想调用 paint 函数时它会给我画另一个圆。这是我的代码:

import java.awt.*;
import javax.swing.*;

public class MyOnto extends JFrame
{
    int weight = 960;
    int heigh = 960;
    int x  = 200;
    int y = 100;

    //Graphics p;

    private static MyOnto my = new MyOnto();

    public MyOnto()
    {
            setTitle("My Ontology");
            setSize(weight, heigh);
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void paint(Graphics g)
    {
            g.setColor(Color.black);
            drawing(g,x,y,100,50);  //g, x ,y, w, h of circle
    }

    public void drawing(Graphics g, int x, int y, int w, int h)
    {
            g.drawOval(x,y,w,h);
            g.drawString("Helo", x+25,y+20);
            x = x + 100;
            y = y + 100;
    }

    public static void main(String[] args)
    {
            //my = new MyOnto();
            my.paint(null);
            my.paint(null); //try to print one more circle
    }

}

输出总是只有一个圆圈。每当我想画一个额外的圆圈时,我怎样才能让它像一个函数调用一样,它只是一个简单的函数调用?

不要覆盖 JFrame 上的 paint()。

自定义绘画是通过重写 JPanel 上的 paintComponent(...) 完成的,然后将面板添加到框架中。

it will draw me another circle.

有两种常见的方法:

  1. 保留要绘制的圆列表
  2. 在 BufferedImage 上绘制圆圈

查看 Custom Painting Approaches 两种方法的工作示例。