我创建了一个自定义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(); }
我已经创建了一个类来在屏幕上绘制这个卡尺,它会这样做,但是如果我试图在屏幕上拖动卡尺,它不会在我拖动时擦除原始形状,所以我会留下一长串形状。我以为我已经从paintComponent(Graphics g)
方法中省略了super.paintComponent(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);
行改为cal = new Calliper(calX, calY, calW, calH);
行,那么它就行了,但有人告诉我不应该这样做。
有什么想法为什么它没有按预期工作吗?
setCalliper()
直接调用build方法,该方法在添加到Path2D
的所有先前点上添加新点,因此每次调用mouseDragged
时,都会向Path添加更多点。在调用build()
之前尝试调用reset()
(或者在moveTo/lineTo调用之前在生成方法中调用reset)。