用Java绘制一个圆圈

时间:2012-04-18 21:30:35

标签: java swing paintcomponent jcomponent

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

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

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

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

1 个答案:

答案 0 :(得分:1)

看起来你在做

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

在错误的地方你不应该画圆圈直到用户放开鼠标,因为那是在设置半径时,在此之前半径是0所以没有画出任何东西。尝试将其移至mouseReleased方法。