Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

drawing a rectangle from right to left, storing rectangle to add more

843806Nov 25 2008 — edited Nov 25 2008
I trying to create a little drawing program right now this program will draw a rectangle for me and fill as the mouse is dragging from left to right but while holding down and reverse to the left it stops at the start point where I clicked my mouse. I don't understand how to allow the rectangle to reverse from right to left during the drag state.

Also I want to keep the rectangle objects on the panel an draw more on top of them in the future. To do this do I need to create another class that somehow stores these rectangle I draw, where or what do I need to look for to learn this.
Thanks for any input.

import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

public class PaintPanel extends JPanel 
{
   private int mpx, mpy; //mouse pressed cords
   private int mrx, mry; //mouse released cords
   private int w, h; //width heights

   // set up GUI and register mouse event handler
   public PaintPanel()
   {
    addMouseListener( new MouseHandler());    
    addMouseMotionListener(new MotionHandler());
   } // end PaintPanel constructor
   
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent e)
      {
         mpx = e.getX();
         mpy = e.getY();   
      }
      
      public void mouseReleased( MouseEvent e)
      {
         mrx = e.getX();
         mry = e.getY();
         repaint();
      }
      
      public void mouseDragged( MouseEvent e )
      {
         mrx = e.getX();
         mry = e.getY();
         repaint();
      }
   }
   
   public class MotionHandler extends MouseAdapter
   {
    public void mouseMoved(MouseEvent e) {}
    public void mouseDragged(MouseEvent e)
    {
	mrx = e.getX();
	mry = e.getY();
        repaint();
    }
   }

   // draw oval in a 4-by-4 bounding box at specified location on window
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); // clears drawing area

      w = Math.abs( mrx - mpx );    //width for rect
      h = Math.abs( mry - mpy );    //heigth for rect
    
      g.setColor(Color.red);
      g.fillRect(mpx,mpy,w,h);
   } // end method paint
} // end class PaintPanel
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 23 2008
Added on Nov 25 2008
4 comments
937 views