Drawing a rectangle over an existing Graphics page

前端 未结 2 1675
猫巷女王i
猫巷女王i 2020-12-21 11:23

I have a Java application which draws a drawing. I want to give the user the possibility to mark an area with the mouse (in order to, for example, zoom into it). For that I

2条回答
  •  无人及你
    2020-12-21 12:10

    You need to repaint on every mouse movement:

        public void mouseDragged(MouseEvent e){
            int x = e.getX();
            int y = e.getY();
            //Update the rectangle holder object with that point coordinates
            repaint();
        }
    

    You'll probably have a holder rectangle object to hold the initial and final rectangle points. The initials are set on mouse click, the final are modified on mouse dragged and on mouse released.

    In paint method, clear the graphics and draw a rectangle with the coordinates in the holder. This is the basic idea.

    UPDATE: How to draw a new shape on top of the existing image: I'm thinking of two options:

    1. If you are only drawing shapes (such as lines, rectangles and other Java2D stuff) you could have a Collection holding these shapes coordinates, and draw all of them on each paint. Pros: good when there are few shapes, allows undoing. Cons: When the number of shapes increase, the paint method will take more and more time in each pass.
    2. Have a "background image". On each paint call, draw first the image and then the currently active shape on top. when an active shape is made persistent (onMouseReleased), it is saved to the background image. Pros: efficient, constant time. Cons: drawing a big background image on every mouse movement could be "expensive".

提交回复
热议问题