如何在JPanel上绘制圆圈? Java 2D [英] How to draw circle on JPanel? Java 2D

查看:390
本文介绍了如何在JPanel上绘制圆圈? Java 2D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPanel,我将一些图像设置为背景。我需要在图像上绘制一堆圆圈。现在圆圈将基于某个坐标x,y定位,并且尺寸将基于某个整数大小。这就是我的课程。

I have a JPanel for which I set some image as the background. I need to draw a bunch of circles on top of the image. Now the circles will be positioned based on some coordinate x,y, and the size will be based on some integer size. This is what I have as my class.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

class ImagePanel extends JPanel {

    private Image img;
    CircleList cList;  //added this

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);

        cList = new CircleList(); //added this
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);

        cList.draw(null); //added this
    }
}

如何创建一些方法能表演吗?

How can I create some method that can performed this?

推荐答案

您的方法可能类似于此,您使用类 CircleList 也包含所有圆圈和绘图例程:

Your approach can be something similar to this, in which you use a class CircleList to hold all the circles and the drawing routine too:

class CircleList
{
  static class Circle
  {
    public float x, y, diameter;
  }

  ArrayList<Circle> circles;

  public CirclesList()
  {
    circles = new ArrayList<Circle>();
  }

  public void draw(Graphics2D g) // draw must be called by paintComponent of the panel
  {
    for (Circle c : circles)
      g.fillOval(c.x, c.y, c.diameter, c.diameter)
  }
}

这篇关于如何在JPanel上绘制圆圈? Java 2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆