用2次鼠标点击画一个圆圈

时间:2012-04-20 10:52:12

标签: java swing

我需要使用鼠标点击来绘制一个简单的圆圈 首先点击将是中心 第二个是半径,圆圈将由2绘制。

提前致谢

1 个答案:

答案 0 :(得分:9)

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

screenshot

生成屏幕截图的代码:

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