gpt4 book ai didi

java - 鼠标拖拽

转载 作者:行者123 更新时间:2023-11-29 08:19:26 26 4
gpt4 key购买 nike

我在显示所有三角形时遇到问题。我使用鼠标拖动绘制了一个三角形。每次我画一个新的三角形,以前的三角形就消失了。怎样才能让三角形留下来,这样绘图面板上就会出现很多三角形?

.....
private class PaintSurface extends JComponent {
Point startDrag, endDrag, midPoint;
Polygon triangle;
public PaintSurface() {
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startDrag = new Point(e.getX(), e.getY());
endDrag = startDrag;
repaint();
}

public void mouseReleased(MouseEvent e) {
Shape r = makeRectangle(startDrag.x, startDrag.y, e.getX(), e.getY());
shapes.add(r);
if (startDrag.x > endDrag.x)
midPoint = new Point((endDrag.x +(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
else
midPoint = new Point((endDrag.x -(Math.abs(startDrag.x - endDrag.x)/2)),e.getY());
int[] xs = { startDrag.x, endDrag.x, midPoint.x };
int[] ys = { startDrag.y, startDrag.y, midPoint.y };
triangle = new Polygon(xs, ys, 3);
startDrag = null;
endDrag = null;
repaint();
}
});

this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
endDrag = new Point(e.getX(), e.getY());
repaint();
}
});
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
paintBackground(g2);
Color[] colors = { Color.YELLOW, Color.MAGENTA, Color.CYAN , Color.RED, Color.BLUE, Color.PINK};
int colorIndex = 0;
g2.setStroke(new BasicStroke(1));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
g2.fillPolygon(triangle);
}
}

最佳答案

您在屏幕上看到的就是您在绘图函数中绘制的内容。目前,您只能在 triangle 变量中存储一个三角形,不断替换和绘制它。

你需要的是存储一个三角形列表,并在 mouseReleased 中每次添加一个新的到列表中。以下是要更改的内容:

private class PaintSurface extends JComponent {
...
//Polygon triangle;
List<Polygon> triangles = new LinkedList<Polygon>();
...

public PaintSurface() {

public void mouseReleased(MouseEvent e) {
...
//triangle = new Polygon(xs, ys, 3);
triangles.add( new Polygon(xs, ys, 3); );
...
}
});
...
}

public void paint(Graphics g) {
...
//g2.fillPolygon(triangle);
for (Polygon triangle : triangles) g2.fillPolygon(triangle);
...
}
}

关于java - 鼠标拖拽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480983/

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