hvordan fjerner jeg en drawLine uden den fjerner det i baggrunden.
Du er nødt til altid at gentegne ALT.
Du kan evt. have en liste af linje objekter som hver indeholder koordinaterne for linjens start og slut punkt:
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
public class Test extends Frame {
private MyCanvas canvas;
private LinkedList<Line> lines;
private Point current = null;
private Point dragDestination = null;
public Test() {
setSize(400, 400);
lines = new LinkedList<Line>();
canvas = new MyCanvas();
add(canvas);
setVisible(true);
}
private class Line {
private Point origin;
private Point destination;
public Line(Point origin, Point destination) {
this.origin = origin;
this.destination = destination;
}
public Point getOrigin() {
return origin;
}
public Point getDestination() {
return destination;
}
}
private class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
current = new Point(e.getX(), e.getY());
} else if (lines.size() > 0) {
lines.removeLast();
canvas.repaint();
}
}
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
lines.add(new Line(current, new Point(e.getX(), e.getY())));
current = null;
canvas.repaint();
}
}
}
private class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
if (current != null) {
dragDestination = new Point(e.getX(), e.getY());
canvas.repaint();
}
}
}
private class MyCanvas extends Canvas {
public MyCanvas() {
addMouseListener(new MyMouseListener());
addMouseMotionListener(new MyMouseMotionListener());
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0,0,getSize().width,getSize().height);
g.setColor(Color.WHITE);
for (Line l : lines) {
g.drawLine(l.getOrigin().x, l.getOrigin().y, l.getDestination().x, l.getDestination().y);
}
if (current != null && dragDestination != null) {
g.drawLine(current.x, current.y, dragDestination.x, dragDestination.y);
}
}
}
public static void main(String args[]) {
new Test();
}
}
Brug venstre muse knap til at tegne linjer. Alle andre muse knapper sletter den sidst tilføjede linje.