开发者

How to draw circle on JPanel? Java 2D

开发者 https://www.devze.com 2022-12-13 06:20 出处:网络
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

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?


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


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消