用Java绘制圆圈

时间:2015-04-15 15:32:26

标签: java swing awt

每当我想调用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
    }

}

输出始终只是一个圆圈。如果我想绘制额外的一个圆圈,它怎么能像函数调用那样使它只是一个简单的函数调用?

1 个答案:

答案 0 :(得分:1)

不要覆盖JFrame上的paint()。

通过在JPanel上覆盖paintComponent(...)来完成自定义绘制,然后将面板添加到框架中。

  它会画另一个圈子。

有两种常见的方法:

  1. 保留要绘制的圆圈列表
  2. 在BufferedImage上绘制圆圈
  3. 查看Custom Painting Approaches了解这两种方法的工作示例。