Java Graphics How to - Detect Clicking inside Ellipse








Question

We would like to know how to detect Clicking inside Ellipse.

Answer

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
/*from  w w w  .  ja  v a  2 s . co  m*/
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {
    List<Ellipse2D> shapes = new ArrayList<Ellipse2D>();
    int w = 400;
    int h = 100;
    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Point2D mouse = new Point2D.Double(0, 0);
    JLabel l = new JLabel(new ImageIcon(img));

    Main() {
        shapes.add(new Ellipse2D.Double(10, 10,20, 30));
        MouseAdapter listener = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent me) {
                mouse = me.getPoint();
                drawImage();
            }
        };
        l.addMouseListener(listener);
        drawImage();

        JOptionPane.showMessageDialog(null, l);
    }

    public void drawImage() {
        Graphics2D g = img.createGraphics();
        RenderingHints hints = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHints(hints);

        g.setStroke(new BasicStroke(4));
        for (Ellipse2D shape : shapes) {
            g.setColor(Color.blue);
            g.fill(shape);
            if (shape.contains(mouse)) {
                g.setColor(Color.RED);
            } else {
                g.setColor(Color.YELLOW);
            }
            g.draw(shape);
        }

        l.setIcon(new ImageIcon(img));

        g.dispose();
    }

    public static void main(String[] args) {
        new Main();
    }
}