Saturday 15 March 2014

swing - Dragging a shape in Java -


I am working on some code to draw a shape (currently a square) around a container (JPNL) . I'm able to pull a blue square and my mouse listener is working because I can pull square. But it is still not doing what I want to do, for the following reasons:

  1. I can only drag the figure vertically, in other words, there is no problem That's how I move my mouse, the shape just moves up or down a diagonal screen.

  2. I can only draw the shape once in other words, if I click inside the shape, drag it to a new position, and then leave the mouse, just go This is - I can not take it more without restarting the program.

    1. Announcement of Droppell class (originally an extension of JPNL):

       < Code> Public category DragPanel introduced the JPNL mouselestoner, Mausomation Listener (Graphics 2DG2; Rectangle 2D class; color color; double x1, y1, x2, y2, size; double offset x, offset y; boolean dragging = false; Constructor method:  
        public drapenel () {x1 = 10.0; y1 = 10.0; size = 40.0; x2 = X1 + size; y2 = y1 + size; square = new rectangle 2d repeat (x1, y1, size , Size); color = color.blue; setFocusable (right); addMouseListener (this); thisMakeConfig (); this.requestFocus ();  
    2. PaintCompany Method, and MouseDragghed, mouse pressed, mouse release methods:

        Public Zero Paint Comonant (Graphics G) {Super. PaintComponent (g); G2 = (Graphics 2D) G; g2 .draw (class); g2.setcolor (color); g2.draw (square);} @ override public wide mousedrug ged (mouse events) {if (dragging) {double mx = EV.X (); Double my = ev.getY (); X1 = MX - Offset X; Y1 = MX - Offset Y; Class = new rectangle 2d. Double (x1, y1, size, size); Repaint (); }} @ Override Public Zero Mouse Mouse Pressed (Mouse Event Eve) {Double MX = Eve. Double my = ev.getY (); If (MX & gt; x1 & amp; mx & lt; x2 & amp; amp;; & gt; y1 & amp; amp; amp; amp; amp; amp; amp; amp; & Amp;; & lt; y2) {dragging = true; Offset x = mx - x1; Offset y = me - y1; }} @ Override Public Wide Moor Released (Mouse Avant AGR 02) {dragging = false; }  

mouse driven ()

  x1 = mx - offset x; Y1 = MX - Offset Y;  

should be

  x1 = mx - offsetX; Y1 = my - offsetY; X2 = x1 + size; Y2 = y1 + size;  

You need to move all the boundaries of Square to them instead of having them explicitly stored in the example variable, I used the built-in rectangular 2D methods to getMinX () and getMaxX ()


No comments:

Post a Comment