gpt4 book ai didi

java - 用Java画一个圆

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:09 25 4
gpt4 key购买 nike

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

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

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

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 方法。

关于java - 用Java画一个圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10218337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com