Solved

Resizing Rectangle

Posted on 2004-04-22
6
867 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
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
bitbucket vs gitbucket 3 55
micro services vs rest web services 16 81
Java Jpanels and Jframe 8 28
configure dependency in POM for new database 3 13
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

930 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now