【问题标题】:Draw a circle using 2 mouse clicks [closed]使用 2 次鼠标点击画一个圆[关闭]
【发布时间】:2012-04-20 19:22:14
【问题描述】:

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

提前致谢

【问题讨论】:

标签: java swing


【解决方案1】:

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

上面生成截图的代码:

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 次分开的点击来做到这一点?
  • 当然!添加了使用两次单击的示例(但我认为在不涉及任何“拖动”的情况下更难看到圆的大小)
  • 谢谢你!你在一个大项目中帮助我
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多