对于我正在做的一个项目,我创建了一个自定义 Path2D 类来在屏幕上绘制一个 H 形“卡尺”。我想拖动并最终调整屏幕上的卡尺大小。我已经成功设置了 Path2D,这样我就可以绘制卡尺了,代码如下所示:
声明和构造函数:
public class Calliper extends Path2D.Double { // X and Y coordinates of all six points on Calliper double cX1, cX2, cX3, cX4, cX5, cX6; double cY1, cY2, cY3, cY4, cY5, cY6; // Width and Height double cWidth; double cHeight; public Calliper(double x, double y, double w, double h) { cWidth = w; cHeight = h; cX1 = x; cY1 = y; cX2 = x; cY2 = y + (h/2); cX3 = x; cY3 = y + h; cX4 = x + w; cY4 = y; cX5 = cX4; cY5 = cY4 + (h /2); cX6 = cX4; cY6 = cY4 + h; build(); }
build() 方法(用于绘制路径)和 setCalliper() 方法,用于重新定义坐标或宽度、高度:
private void build() { // Draw the path for the calliper moveTo(cX1, cY1); lineTo(cX2, cY2); lineTo(cX3, cY3); moveTo(cX2, cY2); lineTo(cX5, cY5); moveTo(cX4, cY4); lineTo(cX6, cY6); } public void setCalliper(double x, double y, double w, double h) { // Rebuild the calliper using different x,y coordinates, or // different width/height cWidth = w; cHeight = h; cX1 = x; cY1 = y; cX2 = x; cY2 = y + (h/2); cX3 = x; cY3 = y + h; cX4 = x + w; cY4 = y; cX5 = cX4; cY5 = cY4 + (h /2); cX6 = cX4; cY6 = cY4 + h; build(); }
我创建了一个类来在屏幕上绘制这个卡尺,它会这样做,但是如果我尝试在屏幕上拖动卡尺,它不会在我拖动时擦除原始形状,所以我得到了一长串形状被留下来。我以为我已经super.paintComponent(g)
从我的paintComponent(Graphics g)
方法中省略了,但即使有它,代码仍然不起作用。
我的拖动方法如下所示:
@Override
public void mouseDragged(MouseEvent ev)
{
double mx = ev.getX();
double my = ev.getY();
if (dragging)
{
calX = mx - offsetX;
calY = my - offsetY;
cal = setCalliper(calX, calY, calW, calH);
repaint();
}
}
如果我将cal = setCalliper(calX, calY, calW, calH);
上面的行更改为 readcal = new Calliper(calX, calY, calW, calH);
那么它可以工作,但我被告知我不应该这样做。
任何想法为什么它不能按预期工作?