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


中心是用户首先在窗口上单击鼠标的位置
半径应为首次单击鼠标与释放鼠标之间(即鼠标拖动)之间的距离的长度。


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

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

最佳答案

看来您正在

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


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

08-19 11:20