I'm basically trying to do something like the classic "Paint" (Microsoft program). But I want to work with layers when drawing. I thought I could use the JPanel component as a layer.
I tested the code below. The goal is to draw a rectangle with the mouse. There is a temporary level (temp) for drawing on it when dragging the mouse, and there is an actual layer (area) for drawing when the mouse is released. But every time I start drawing a new rectangle, the old ones disappear. Also, if I run setVisible (false) again and true, everything will disappear.
MouseInputAdapter mia = new MouseInputAdapter() { private int startx = 0, starty = 0, stopx = 0, stopy = 0; public void mousePressed(MouseEvent evt) { startx = evt.getX(); starty = evt.getY(); } public void mouseDragged(MouseEvent evt) { Graphics2D tempg = (Graphics2D) temp.getGraphics(); int width = Math.abs(startx - evt.getX()); int height = Math.abs(starty - evt.getY()); int x = evt.getX(), y = evt.getY(); if(x > startx) x = startx; if(y > starty) y = starty; Rectangle r = new Rectangle(x, y, width, height); tempg.clearRect(0, 0, getWidth(), getHeight()); tempg.draw(r); } public void mouseReleased(MouseEvent evt) { Graphics2D g = (Graphics2D) area.getGraphics(); stopx = evt.getX(); stopy = evt.getY(); int width = Math.abs(startx - stopx); int height = Math.abs(starty - stopy); int x = startx, y = starty; if(x > stopx) x = stopx; if(y > stopy) y = stopy; Rectangle r = new Rectangle(x, y, width, height); g.draw(r); } }; area.addMouseListener(mia); area.addMouseMotionListener(mia); temp.addMouseListener(mia); temp.addMouseMotionListener(mia);
What is wrong with this code?
source share