I recently wrote a similar type of application. Here is a screenshot. It is not fully developed, as you can see. 
Now I am also having similar problems that you are currently facing. What do you need to do.
- Double buffer for all drawing operations.
- Do not clear the screen causing redrawing.
Repaint actually fills the screen with the background color first, and this is the flicker that you see.
You can make a copy of the current screen canvas in Image . Image will be updated after each drawing process. Instead of clearing the screen by invoking Repaint , what you do is draw an Image on the canvas. This is like double buffering.
In code, you call Repaint every time the mouse is dragged. This is the cause of the flicker.
UPDATE
Three main questions I found in your updated code
- In the
drawWhileDragging method drawWhileDragging you do not change the color for drawing the context of the GUI. Thus, the line is drawn in black, and your background is also black. As a result, you see nothing. - In the same method, you pass a graphical context (for example, a link) to
drawingImage . As a result, the line is actually drawn on the screen, not on the screen. - In
mouseDragged you trigger a redraw after every drag and drop. As a result, nothing is drawn.
I ran my code on my machine and made the necessary changes. I leave only modified methods to save it.
Here is the updated mouseDragged method
public void mouseDragged(MouseEvent e) { System.out.println("Dragged"); isDragMode = true; dragPoint.x = e.getX(); dragPoint.y = e.getY(); switch (shapeString) { case "Line": shape.setDragPoint(dragPoint.x, dragPoint.y); //here i set the drag points to the already created line at step 1 break; case "FreeHand": shape = new FreeShape(); break; } getGraphics().drawImage(drawingImage, 0,0,null); //Added this line shape.drawWhileDragging(getGraphics()); // i call this method to draw while mouse is dragging }
Below is the updated drawWhileDragging method
void drawWhileDragging(Graphics g) { g.setColor(Color.ORANGE); g.drawLine(startPoint.x, startPoint.y, currentPoint.x, currentPoint.y); g.setColor(Color.BLACK); }
Well, I set the color to orange. You need to set the color according to the Choice menu.
You can implement a similar analogy for drawing other shapes.
source share