1

我想画一个具有以下属性的圆圈:

  • 中心是用户在窗口上第一次点击鼠标的点
  • 半径应该是第一次单击鼠标和释放鼠标(即鼠标拖动)之间的距离长度。

这是我到目前为止所拥有的,但它没有做我需要做的事情:

package assignment;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

public class DrawCircle extends JFrame implements MouseListener
{
    private int centerX;
    private int centerY;
    private int endPtX;
    private int endPtY;
    private double radius;
    private double w;
    private double h;
    private CirclePanel circPanel;

    /** constructor **/
    public DrawCircle() 
    {
        this.setTitle("Click to Draw Circle");
        this.setSize(500, 500);
        this.setPreferredSize(new Dimension(500, 500));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setResizable(false);
        this.addMouseListener(this);
        this.circPanel = new CirclePanel();
        this.circPanel.setPreferredSize(new Dimension(500, 500));
        this.add(this.circPanel);
        pack();
    }

    public void mousePressed(MouseEvent e)
    {
        centerX = e.getX();
        centerY = e.getY();
        circPanel.set(centerX, centerY, radius, radius);
        repaint();
        pack();
    }

    public void mouseReleased(MouseEvent e)
    {
        endPtX = e.getX();
        endPtY = e.getY();

        radius = Math.sqrt(Math.pow(endPtX - centerX, 2) + Math.pow(endPtY - centerY, 2));
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e){}



    //circle panel
    private class CirclePanel extends JComponent
    {
        private int x;
        private int y;
        private int w;
        private int h;

        public void set(int x, int y, double width, double height)
        {
            this.x = x;
            this.y = y;
            w = (int) width;
            h = (int) height;
        }

        public void paintComponent(Graphics g)
        {
            g.drawOval(x, y, w, h);
        }
    }

    //main method
    public static void main (String [] args)
    {
        new DrawCircle();
    }
}
4

1 回答 1

1

看起来你正在做

circPanel.set(centerX, centerY, radius, radius);
repaint();
pack();

在错误的位置,您不应该在用户放开鼠标之前绘制圆,因为那是设置半径的时候,而在此之前半径为 0,因此没有绘制任何内容。尝试将其移至mouseReleased方法。

于 2012-04-18T21:34:12.663 回答