我在显示所有三角形时遇到问题。我使用鼠标拖动绘制一个三角形。每次我画一个新的三角形,前一个三角形就消失了。我怎样才能让三角形留下来,所以绘图面板上会有很多三角形?
.....
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);
}
}