How to draw circle on JPanel? Java 2D

我与影子孤独终老i 提交于 2019-11-28 13:02:11
Jack

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

Well, you will probably want to create an ArrayList to store the information about the circles to be drawn. Then when the paintComponent() method is invoked you just loop through the ArrayList and draw the circles.

Custom Painting Approaches shows how this might be done for a rectangle. You can modify the code for an oval as well you would probably add methods to update the Array with the location information rather than by doing it dynamically.

Easiest thing to do would be to place something along these lines into your paintComponent method.

int x = ...;
int y = ...;
int radius = ...;
g.drawOval(x, y, radius, radius);

Have you looked at JXLayer? It's an awesome library that allows you to layer special painting on top of any GUI element in an obvious way. I believe that will be included in the main java libraries for JDK7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!