I am trying to write a program that displays a rectangle when user drag the mouse and when user release mouse, it displays the rectangle with green color.

I am terribly confused here is what I am thinking to do

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class DragRectangle extends JApplet
{
  public void paint(Graphics g)
  {
      super.paint(g)
  }
  public void mouseDragged(MouseEvent e)
  {
    e.setColor(Color.GREEN) 
      e.drawRect(I am not sure what the coordinate will be)
      repaint();
   }

Am I in right track? Any suggestion or help will be highly appreciated!!

I've never used MouseListener, but your mouseDragged code is wrong. "e" refers to a MouseEvent object, NOT your rectangle. Lets say you had an Object that represented your rectangle, here's what your code should look similar to.

//Note this shouldn't be of type object, I'm just showing that it is an object
Object myRectangle;


public void mouseDragged(MouseEvent e){
Object source= e.getSource();

if (source == myRectangle){
myRectangle.setColor(whatever.GREEN);
//call some repaint method here
}

}

Correct. The mouse event will supply the current coordinates of the mouse, which you can use to calculate your new rectangle coordinates. The paintComponent() method can then draw a rectangle with those coordinates when you call repaint().

Sorry, I didn't get you. I understand that I cant use e, So I am using 'event' as my object.
Where you get that myREctangle? is that an object????
Thanks ,

Ezzaral, can you show me some steps please?
so, am I in the right track????

This should give you a start to work from. Similar, but different enough that you'll have to figure out the rectangle part.

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

public class PaintApplet extends JApplet {

    public void init() {
        getContentPane().add(new CanvasPanel());
    }

    class CanvasPanel extends JPanel implements MouseMotionListener{
        Color backColor = Color.WHITE;
        Color foreColor = Color.BLUE;
        
        Point p0 = new Point(0,0);
        Point p1 = new Point(0,0);
        
        public CanvasPanel(){
            super();
            addMouseMotionListener(this);
        }

        @Override
        protected void paintComponent(Graphics g) {
            g.setColor(backColor);
            g.fillRect(0, 0, getWidth(), getHeight());
            g.setColor(foreColor);
            g.drawLine(p0.x, p0.y, p1.x, p1.y);
        }

        public void mouseDragged(MouseEvent e) {
            p1.x = e.getX();
            p1.y = e.getY();
            repaint();
        }

        public void mouseMoved(MouseEvent e) {
            // nothing here - just want drag operations
        }
    }
}

so far I got upto this part! can anyone help me how to proceed from here:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class DragRectangle extends JApplet
{
    private int previousX, previousY;
    private boolean drag;
 /* public void init()
  {
      addMouseDragged(this);
      addMouseReleased(this);
  }*/
  public void paint(Graphics g)
  {
      super.paint(g);
  }
  public void mouseDragged(MouseEvent event)
  {
      //e.setColor(Color.GREEN)
      //e.drawRect(
      if(drag==false)
      {
          return;
      }

      int x = event.getX();
      int y = event.getY();
      previousX=x;
      previousY=y;
      //Graphics g = getGraphics();
      //event.setColor(Color.YELLOW);
      //event.drawRect(x,y,10,20);
  }
  public void mouseReleased(MouseEvent evt)
  {
      g.setColor(Color.YELLOW);
      g.drawRect(previousX, previousY, getWidth(),getHeight());
      repaint();
  }

}

thanks

@complexcodes
Seems like you are confused in using CODE tags use [ CODE=java] and [ /CODE ] (without the spaces between CODE and brackets)to cover your java code.

Why not start with the applet that I wrote for you that is very close to what you want to do? Did I completely waste my time trying to give you a simple, solid starting point?

If you will glance at that code, notice that all operations using the Graphics class occur in the paintComponent() method and those method calls just use the coordinate variables in the class. The mouse listener alters those coordinates based upon the x and y values supplied by the mouse event and then calls repaint(), which in turn calls paintComponent() as part of the rendering process.

All you need to do is alter the code in the mouse listener and the paintComponent() method to draw your rectangle instead of the simple line I used as an example.

@stephen84s

To exclude a piece of text as being interpreted as BBCode, use the noparse tag. With the use of noparse, you can write something along the lines of [noparse][code=java]your code here[/code][/noparse] and be sure it won't be interpreted by the BBCode parser of vBulletin.

Ezzarel, I did run the applet with the code you provided. I am confused if I have to use that canvas mentioned in your code.
Here is my updated code, and I am getting one compile error. Can you plese check if my logic is correct :-

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class DragRectangle extends JApplet implements MouseListener
{
	private int previousX, previousY;
	private boolean drag;
  public void init()
  {
	  addMouseListener(this);

  }
  public void paint(Graphics g)
  {
	  super.paint(g);
	  g.setColor(Color.YELLOW);
	  g.drawRect(previousX, previousY, getWidth(), getHeight());
  }
  public void mouseDragged(MouseEvent event)
  {

	  if(drag==false)
	  {
		  return;
	  }

	  int x = event.getX();
	  int y = event.getY();
	  previousX=x;
	  previousY=y;

  }
  public void mouseReleased(MouseEvent evt)
  {
	  
	  repaint();
  }

}

compile error:-
C:\Documents and Settings\Owner\My Documents\java\DragRectangle.java:6: DragRectangle is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
public class DragRectangle extends JApplet implements MouseListener
^
1 error

Tool completed with exit code 1

That error is because when you implement a class (which you did by saying DragRectangle implements MouseListener) you have to have all of the methods from the class.

Example: lets say these are the methods from MouseListener:

int mouseStuff();
Object moreMouseStuff();
Object otherMouseStuff();

That would mean that any time you write a class that 'implements MouseListener', your class would have to include the methods mouseStuff, moreMouseStuff, and otherMouseStuff. Specifically, the compiler is complaining because you need to have a method in your class that is declared as follows:

public void mouseExited(MouseEvent e){
}

(Side note: what is the point of the code in your mouseDragged method that says if (drag==false)? It seems to me that you never initialized the variable, dragged. Also, it seems like the variable is useless anyway, since if mouseDragged gets called, its guaranteed that the mouse was dragged.)


Note: to the kid who is having trouble, you can ignore everything I say after this line... pay attention to what I said above. Everything after this point is directed at Ezzaral & others.
Documentation for the class can be found here:
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseListener.html
If you read the documentation, it says that mouseDragged is NOT a method supported by the class, so I am confused why he implemented it. It says to use MouseMotionListener. Am I looking at the wrong documentation somehow?

edit: I looked at the documentation for MouseMotionListener & back at Ezzeral's code, and it turns out that the kid just implemented the wrong class. So nevermind my confusion.

so, how can I fix it? just by removing that line?

No, that will not solve your problem. The problem is that there are methods that you need to implement which you didn't implement. Specifically, you need to implement the mouseExited method. To do that, all you need to do is put the mouseExited method in your code.

Actually, you DO need to erase the part where it says "MouseListener", but not for the reason that you think. You were supposed to implement MouseMotionListener. So where it says MouseListener, change it MouseMotionListener. Then, go to the Java API for that class. (Link: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/MouseMotionListener.html). Go to the method summary and make sure that you have each of the methods in your code. Currently, you only have the mouseDragged method in your code, so you will have to add the mouseMoved method to your code.

Also, since you don't yet know how implementing classes works, GO READ THE JAVA TUTORIALS!

Interfaces:
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

what code goes inside the two methods, mouseExited and mouseMoved?
This problme turns out to be harder than I thought!

Thanks,

Read the link I gave you about MouseMotionListener. The method detail for mouseDragged states that as the user drags the mouse, MouseEvents continue to occur until the user stops by unclicking. Therefore, if you want the Rectangle to move wherever the user drags it, then you would have to call the repaint() method inside your mouseDragged code. The code that you posted earlier, in mouseDragged in post #11, will be useful for knowing where the mouse currently is. If you read the method details for mouseDragged, you will also notice that it will probably not help you with the part about "I want the rectangle to be green when the user stops dragging it." To make the Rectangle green, you will need to look into other methods. Hint: look into the MouseListener interface. You can do this by googling for Java MouseListener.

I dont want my rectangle to be filled with green while dragging, rather I want my recatngle to be filled when I release my mouse(done with dragging). I dont think I need repaint method in mouseDragged method, do I?
Also, in mouse moved method, do I need to keep track of the coordinates?
This thing is so so so confusing! first time I am doin something related to mouseListener class

What I was saying in my last post is that you want the Rectangle to be moved to wherever you drag your mouse on the screen. This can be done by putting the correct code in mouseDragged. You also want the Rectangle to be colored green when the user unclicks. This can be done by implementing MouseListener, then putting the correct code in the correct method (read the description of the methods in the MouseListener javadoc!). So, in summary, you have to implement both MouseMotionListener and MouseListener.

When repaint() is called, I'm pretty sure it calls paintComponent. So you would have to write the code that does the actual redrawing of the Rectangle based on its position in paintComponent. But when you want to change the Rectangle's color, you can just put the code to change the color in the method that detects when the user unclicks. Then, right after that, you'd say repaint() so that the color change takes effect.

If you need clarification of anything I just said, I will clarify. Beyond that, I won't help anymore unless you post code and ask specific questions about it.

how can I make the rectangle disappear after I click the mouse anywhere in applet?
what line of codes do I need to add?

Thanks,
here is my working version of code:-

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

	public class DragRectangle extends JApplet
	{
		private Point coordinate1[]=new Point[20];
		private Point coordinate2[]=new Point[20];
		private Point beg=new Point();
		private Point last=new Point();
		private int pointCounter=0;
		Rectangle rect = new Rectangle();

		public void  DrawRectangle()
		{
			addMouseMotionListener(new MouseMotionAdapter()
			{
				public void mouseDragged(MouseEvent ev)
				{
				  last = ev.getPoint();
				  rect.setFrameFromDiagonal(beg,last);
				  repaint();
				}
			});
			addMouseListener(new MouseAdapter()
			{
			  public void mousePressed(MouseEvent e)
			  {
				beg = e.getPoint();
			  }

			  public void MouseReleased(MouseEvent ev)
			  {
				coordinate1[pointCounter]=beg;
				coordinate2[pointCounter]= ev.getPoint();
				pointCounter ++;
				rect.setFrameFromDiagonal(beg,beg);
				repaint();
			  }
		   });
		 }
		 public void paint(Graphics g)
		 {
			super.paint(g);
			Graphics2D g2 = (Graphics2D)g;
			g2.setPaint(Color.black);
			g2.draw(rect);
		    g2.setPaint(Color.yellow);
			Rectangle rect2 = new Rectangle();
			for (int i =0; i < pointCounter; i++)
			{
				rect2.setFrameFromDiagonal(coordinate1[i], coordinate2[i]);
				g2.fill(rect2);
			}
		  }
	  }

Thanks,

I know the code goes in mouseClicked(MouseEvent e)
My question is what would my code be like in that method? any help, sir???

I'm really not sure how you would do that. You should look into the documentation for the various methods you've been using, such as the ones that you are currently using in your paint method. For example, what would happen if you set both the rectangle's length and width to 0 then called repaint? It seems like this would lead to a rectangle with 0 area, which would be painted as nothing on your screen. That probably isn't the best way to go about things, in fact - probably the worst way you could do it - but it will probably work. If you want a better solution, which I'd hope you do, then look into the methods you are using. They have documentation which tells you what happens based on the parameters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.