Click here to Skip to main content
15,065,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

It should work like in MSPaint. The line should follow the mouse as the mouse is dragged.

What I did is:
private int xBegin;
private int yBegin;

private void drawPanelMousePressed(java.awt.event.MouseEvent evt)
     xBegin = evt.getX();
     yBegin = evt.getY();

private void drawPanelMouseDragged(java.awt.event.MouseEvent evt) {
       Graphics g = drawPanel.getGraphics()
       g.drawLine(xBegin, yBegin, evt.getX(), evt.getY());

The problem is: It draws new lines as mouse is dragged. Somehow I should remember the original graphics before mouse is pressed. Adding a field and initializing it during mousePress did not work. Probably I have to clone the Graphics object. How can I do that? Or are there any easier ways?

mygraphics.create() method did not work either.
Updated 13-Oct-10 9:59am

1 solution

Check this code, this is Pain like program written in Java. SimplePaint[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900