1
我必須在鼠標移動時繪製線條,點擊鼠標後,線條應繼續繪製直至雙擊。 說點A,點B和點C,當點擊鼠標點A時,應該開始畫線。當在點B上點擊鼠標時,前導線應該在那裏,新線應該從點B開始繪製,除非雙擊。點C應該是相同的,等等,直到鼠標被雙擊。經過一番研究,我寫了下面的代碼,它工作得很好,但它適用於拖動NOT MOUSE MOVE事件,我試圖將代碼傳輸到mouseMoved事件,但prev行正在消失。有人可以幫我解決這個問題嗎?爲每次鼠標點擊繪製線條並在雙擊時停止繪製
public class WorkingLines {
public WorkingLines() {
JFrame jf = new JFrame("Free Hand Drawing Example");
Board draw = new Board();
jf.add(draw);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(600, 500);
jf.setVisible(true);
}
public static void main(String a[]) {
new WorkingLines();
}
}
class Board extends JPanel implements MouseListener, MouseMotionListener {
ArrayList<pts> list = new ArrayList<pts>();
Point start, end;
public Board() {
start = null; /* Initializing */
end = null;
// this.setBackground(Color.BLACK);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
super.paint(g2);
// g.setColor(Color.BLACK);
for (pts p : list) {
System.out.println("Drawing Lines!!!=>");
g.drawLine((int) p.getStart().getX(), (int) p.getStart().getY(), (int) p.getEnd().getX(),
(int) p.getEnd().getY());
}
if (start != null && end != null) {
System.out.println("Drawing happening!!!=>");
g.drawLine(start.x, start.y, end.x, end.y);
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent me) {
start = me.getPoint();
System.out.println("Start initialized!!");
for (pts pt : list) {
System.out.println("Point x coordinate =>" + pt.start.getX());
}
repaint();
}
@Override
public void mouseReleased(MouseEvent me) {
end = me.getPoint();
pts pt = new pts(start, end);
list.add(pt);
repaint();
if (me.getClickCount() == 2) {
start = null;
end = null;
}
}
@Override
public void mouseDragged(MouseEvent me) {
System.out.println("Mouse Moved=>" + start);
end = me.getPoint();
repaint();
}
@Override
public void mouseMoved(MouseEvent me) {
}
}
class pts {
Point start = null;
Point end = null;
public pts(Point start, Point end) {
this.start = start;
this.end = end;
}
public Point getStart() {
return this.start;
}
public Point getEnd() {
return this.end;
}
}