Solved

Resizing Rectangle

Posted on 2004-04-22
6
879 Views
Last Modified: 2012-08-13
Hi All,

Iam writing a program implementing drag and drop. I have dragged and droppped a rectangle on to the JPanel now iam able to move the rectangle all over the panel.

Now all I need is to resize the rectangle from any of its end points and if possible insert an editable text area inside the rectangle. If anyone could help me with this i would be thankful.

This is my code.

public class Tester extends JFrame
{
myCanvas canvas;
private Image image;
int x;
int y;
int width;
int height;
Cursor prevCursor = null;
public Tester()
{
super("Tester");
ImageIcon image1 = new ImageIcon("button1.gif");
button button1 = new button(image1);
ImageIcon image2 = new ImageIcon("button2.gif");
button button2 = new button(image2);
button2.setTransferHandler(new TransferHandler("text"));
JToolBar bar = new JToolBar();
bar.add(button1);
bar.add(button2);
canvas = new myCanvas();
canvas.reshape(0,0,500,500);
MouseListener listener = new DragMouseAdapter();
button2.addMouseListener(listener);
Panel pane = new Panel();
BorderLayout bord = new BorderLayout();
pane.setLayout(bord);
pane.add("North", bar);
pane.add("Center",canvas);
pane.setVisible(true);
getContentPane().add(pane);
image = getToolkit().getImage("images.jpg");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(image, 0);
try
{
      tracker.waitForID(0);
}
catch(InterruptedException e)
{
      System.out.println("Exception Occured" + e);
}
x = 300;
y = 100;
width = image.getWidth(this);
height = image.getHeight(this);
prevCursor = getCursor();
}                        
public void updateImages()
{
canvas.repaint();
}
public class button extends JButton implements  DragSourceListener, DragGestureListener  
{
DragSource dragSource = null;
public button(ImageIcon image1)
      {
            super(image1);
            dragSource = new DragSource();
            dragSource.createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_MOVE, this);
      }
public void dragDropEnd (DragSourceDropEvent event)
      {  
      }
public void dragEnter (DropTargetDragEvent event)
      {
            System.out.println( "DRAG ENTER");
            event.acceptDrag (DnDConstants.ACTION_MOVE);
      }
public void dragOver (DropTargetDragEvent event)
      {
            System.out.println( "DRAG OVER");
      }
public void dropActionChanged ( DropTargetDragEvent event )
      {
      }
public void dragGestureRecognized( DragGestureEvent event)
      {
      }
public void dragEnter (DragSourceDragEvent event)
      {
            System.out.println( " DRAG ENTER");
      }
public void dragExit (DragSourceEvent event)
      {
            System.out.println( "DRAG EXIT");
      }
public void dragOver (DragSourceDragEvent event)
      {
            System.out.println( "DRAG EXIT");
      }
public void dropActionChanged ( DragSourceDragEvent event)
      {
            System.out.println( "DROP ACTION CHANGED");
      }
}
public class myCanvas extends JPanel implements  DropTargetListener,MouseListener,MouseMotionListener
{
DropTarget dropTarget = null;
HashMap objects = new HashMap();
public myCanvas()
{
      super(new BorderLayout());
      dropTarget = new DropTarget (this, this);
      addMouseMotionListener(this);
      addMouseListener(this);
}
public void dragDropEnd (DragSourceDropEvent event)
{  
System.out.println("Dropped");
}
public void dragEnter (DropTargetDragEvent event)
{                              
System.out.println( "DRAG ENTER");
event.acceptDrag (DnDConstants.ACTION_MOVE);
}
public void dragExit (DropTargetEvent event)
{
System.out.println( "DRAG EXIT");
}
public void dragOver (DropTargetDragEvent event)
{
System.out.println( "DRAG OVER");
}
public void drop (DropTargetDropEvent event)
{
System.out.println("DROPPED");  
try {
Point p = event.getLocation();
addElement(event.getSource(), p);
event.getDropTargetContext().dropComplete(true);
}
catch(Exception e)
{
e.printStackTrace(System.out);
}
}
public void dropActionChanged ( DropTargetDragEvent event )
{
}
public void dragGestureRecognized( DragGestureEvent event)
{
}
public void dragEnter (DragSourceDragEvent event)
{
System.out.println( " DRAG ENTER");
}
public void dragExit (DragSourceEvent event)
{
System.out.println( "DRAG EXIT");
}
public void dragOver (DragSourceDragEvent event)
{
System.out.println( "dragExit");
}
public void dropActionChanged ( DragSourceDragEvent event)
{
System.out.println( "DROP ACTION CHANGED");
}
public void addElement( Object o, Point p)
{
System.out.println("Trying to add to canvas ");
if(!objects.containsKey(p))
objects.put(p,o);
canvas.repaint();
}       
public void paint(Graphics g)
{
System.out.println(" Print called ");
super.paint(g);
g.drawRect(0,0,1020,650);
g.setColor ( Color.white );
g.fillRect (1,1,1021,651);
g.setColor ( Color.blue );
for(Iterator i=objects.keySet().iterator(); i.hasNext(); )
{
Point p = (Point)i.next();
g.drawRect((int)p.getX(),(int)p.getY(),45,45);
}
}
public void setImageX(int a)
{
x = a;
}
public void setImageY(int a)
{
y = a;
}
public void setImageHeight(int h)
{
height = h;
}
public void setImageWidth(int w)
{
width = w;
}
public int getImageX()
{
return x;
}
public int getImageY()
{
return y;
}
public int getImageHeight()
{
return height;
}
public int getImageWidth()
{
return width;
}
public void mouseDragged(MouseEvent evt)
{      
if(prevP == null)
{
      System.out.println("OutSide Image");
      return;
}      
Point newP = new Point(evt.getX(), evt.getY());                      
if(!objects.containsKey(newP))
{
      objects.put(newP, objects.get(prevP));
      objects.remove(prevP);
}
      prevP = newP;
      repaint();
      updateImages();
}
public void mouseMoved(MouseEvent evt)
{
if(evt.getX() > getImageX() && evt.getX() < (getImageX()+getImageWidth()))
if(evt.getY() > getImageY() && evt.getY() < (getImageY()+getImageHeight()))
{
      System.out.println("On The Image");
}
else
{
      setCursor(prevCursor);
}
}
public void mousePressed(MouseEvent evt)
{      
for(Iterator i=objects.keySet().iterator(); i.hasNext(); )
{
      Point p = (Point)i.next();
if(evt.getX() > p.getX() && evt.getX() < (p.getX()+getImageWidth()))
if(evt.getY() > p.getY() && evt.getY() < (p.getY()+getImageHeight()))
{
      prevP = p;
      return;
}
}
}
public void mouseReleased(MouseEvent evt)
{
prevP = null;
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
Point prevP = null;
}
private class DragMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
private static void createAndShowGUI()
{
Tester frame = new Tester();
frame.pack();
frame.setVisible(true);
}
public static void main(String[] arguments)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Thanks in advance.
0
Comment
Question by:mentor_dave
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 10887296
It's always handy to
- layout your code well/better before posting
- also mention the imports:

import javax.swing.*;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.util.*;


How do you move a dropped rectangle?
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10887456
look at this , it may help you..

http://www.oreilly.com/catalog/jswing/chapter/ch09.html

Best of Luck..

R.K.
0
 
LVL 9

Accepted Solution

by:
mmuruganandam earned 300 total points
ID: 10887464

      public class myCanvas extends JPanel implements DropTargetListener, MouseListener, MouseMotionListener
      {
            DropTarget dropTarget = null;
            HashMap objects = new HashMap();
            boolean isResize = false;
            int rectWidth = 45;
            int rectHeight = 45;

            public myCanvas()
            {
                  super(new BorderLayout());
                  dropTarget = new DropTarget(this, this);
                  addMouseMotionListener(this);
                  addMouseListener(this);
            }
            public void dragDropEnd(DragSourceDropEvent event)
            {
                  System.out.println("Dropped");
            }
            public void dragEnter(DropTargetDragEvent event)
            {
                  System.out.println("DRAG ENTER");
                  event.acceptDrag(DnDConstants.ACTION_MOVE);
            }
            public void dragExit(DropTargetEvent event)
            {
                  System.out.println("DRAG EXIT");
            }
            public void dragOver(DropTargetDragEvent event)
            {
                  System.out.println("DRAG OVER");
            }
            public void drop(DropTargetDropEvent event)
            {
                  System.out.println("DROPPED");
                  try
                  {
                        Point p = event.getLocation();
                        addElement(event.getSource(), p);
                        event.getDropTargetContext().dropComplete(true);
                  }
                  catch (Exception e)
                  {
                        e.printStackTrace(System.out);
                  }
            }
            public void dropActionChanged(DropTargetDragEvent event)
            {
            }
            public void dragGestureRecognized(DragGestureEvent event)
            {
            }
            public void dragEnter(DragSourceDragEvent event)
            {
                  System.out.println(" DRAG ENTER");
            }
            public void dragExit(DragSourceEvent event)
            {
                  System.out.println("DRAG EXIT");
            }
            public void dragOver(DragSourceDragEvent event)
            {
                  System.out.println("dragExit");
            }
            public void dropActionChanged(DragSourceDragEvent event)
            {
                  System.out.println("DROP ACTION CHANGED");
            }
            public void addElement(Object o, Point p)
            {
                  System.out.println("Trying to add to canvas ");
                  if (!objects.containsKey(p))
                        objects.put(p, o);
                  canvas.repaint();
            }
            public void paint(Graphics g)
            {
                  System.out.println(" Print called ");
                  super.paint(g);
                  g.drawRect(0, 0, 1020, 650);
                  g.setColor(Color.white);
                  g.fillRect(1, 1, 1021, 651);
                  g.setColor(Color.blue);

                  for (Iterator i = objects.keySet().iterator(); i.hasNext();)
                  {
                        Point p = (Point) i.next();

                        if (isResize)
                        {
                              rectWidth += 10;
                        }
                        g.drawRect((int) p.getX(), (int) p.getY(), rectWidth, rectHeight);
                  }
            }
            public void setImageX(int a)
            {
                  x = a;
            }
            public void setImageY(int a)
            {
                  y = a;
            }
            public void setImageHeight(int h)
            {
                  height = h;
            }
            public void setImageWidth(int w)
            {
                  width = w;
            }
            public int getImageX()
            {
                  return x;
            }
            public int getImageY()
            {
                  return y;
            }
            public int getImageHeight()
            {
                  return height;
            }
            public int getImageWidth()
            {
                  return width;
            }
            public void mouseDragged(MouseEvent evt)
            {
                  if (prevP == null)
                  {
                        System.out.println("OutSide Image");

                        if (isResize == false)
                              return;
                  }
                  else
                  {
                        Point newP = new Point(evt.getX(), evt.getY());
                        if (!objects.containsKey(newP))
                        {
                              objects.put(newP, objects.get(prevP));
                              objects.remove(prevP);
                        }
                        prevP = newP;
                  }

                  repaint();
                  updateImages();

                  System.out.println("resize: " + isResize);
            }
            public void mouseMoved(MouseEvent evt)
            {
                  if (evt.getX() > getImageX() && evt.getX() < (getImageX() + getImageWidth()))
                        if (evt.getY() > getImageY() && evt.getY() < (getImageY() + getImageHeight()))
                        {
                              System.out.println("On The Image");
                        }
                        else
                        {
                              setCursor(prevCursor);
                        }

                  if (isResize)
                  {
                        System.out.println("doing...");
                        updateImages();
                  }
            }
            public void mousePressed(MouseEvent evt)
            {
                  for (Iterator i = objects.keySet().iterator(); i.hasNext();)
                  {
                        Point p = (Point) i.next();

                        System.out.println(evt.getPoint() + "#" + p);

                        if ((evt.getX() == p.getX()) && (evt.getY() == p.getY()))
                        {
                              isResize = true;
                        }

                        if (evt.getX() > p.getX() && evt.getX() < (p.getX() + getImageWidth()))
                              if (evt.getY() > p.getY() && evt.getY() < (p.getY() + getImageHeight()))
                              {
                                    prevP = p;
                                    return;
                              }

                        if (isResize)
                        {
                              System.out.println("doing...");
                              updateImages();
                        }

                  }
            }
            public void mouseReleased(MouseEvent evt)
            {
                  if (isResize)
                  {
                        System.out.println("Done...");
                        isResize = false;
                  }

                  prevP = null;
            }
            public void mouseClicked(MouseEvent evt)
            {
            }
            public void mouseEntered(MouseEvent evt)
            {
            }
            public void mouseExited(MouseEvent evt)
            {
            }
            Point prevP = null;
      }


I have done few modifications on your mycanvas.  

click on the exact top left corner of the rectangle and move anyside.  The rectangle will grow in width side.  
Change your code for exact need.

This is a simple example for  you to handle the resize in different place.

I was not able to resize your rectangle as there is no gap in your design to fit certain things in.


Regards,
Muruga
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

Author Comment

by:mentor_dave
ID: 10917608
Thanks a lot Mr.Muruganandam
but can i do the same by clicking from any end point.
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10917624
You can but... you have to customize the program a bit
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10927290
thank you :-)
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question