使用 2 次鼠标点击绘制一个圆圈 [英] Draw a circle using 2 mouse clicks

查看:40
本文介绍了使用 2 次鼠标点击绘制一个圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用鼠标点击画一个简单的圆圈第一次点击将成为中心其次是半径,圆将由 2 绘制.

I need to draw a simple circle by using mouse clicks First click will be the center Second will be the radius and the circle would be draw by the 2.

提前致谢

推荐答案

好问题!下面的代码是一个自包含的示例(我使用拖动来定义半径):

Good question! The code below is a self contained example (I'm using dragging to define the radius):

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame("Test");
    frame.add(new JComponent() {
        Point p; int r; 
        {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    p = e.getPoint(); r = 0; repaint();
                }
                public void mouseReleased(MouseEvent e) {
                    r = (int) Math.round(e.getPoint().distance(p));
                    repaint();
                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {
                    r = (int) Math.round(e.getPoint().distance(p));
                    repaint();
                }
            });
            setPreferredSize(new Dimension(400, 300));
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if(p != null) g.drawOval(p.x - r, p.y - r, 2 * r, 2 * r); 
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

<小时>

使用 2 次点击的示例:

public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame("Test");
    frame.add(new JComponent() {
        Point p1, p2;
        {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (p1 == null || p2 != null) { 
                        p1 = e.getPoint();
                        p2 = null;
                    } else {
                        p2 = e.getPoint();
                    } 
                    repaint();
                }
            });
            setPreferredSize(new Dimension(400, 300));
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if(p1 != null && p2 != null) {
                int r = (int) Math.round(p1.distance(p2));
                g.drawOval(p1.x - r, p1.y - r, 2 * r, 2 * r);
            }
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

这篇关于使用 2 次鼠标点击绘制一个圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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