Hey there,
I am trying to build an application that listens to my mouse. once I click on my panel, it reads the x, y coordinates of the point I clicked on. Second time I click the panel, it reads the x, y coordinates of this other point and draws a line from the first point to the second.
Here is my code:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class HelloFromVenus extends Applet implements MouseListener
{
LineSegment ls = new LineSegment();
boolean firstclick = false;
int i = 0;
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
g.fillRect(0, 0, 400, 400);
ls.draw(g);
addMouseListener(this);
}
public void mouseClicked(MouseEvent ev)
{
Point p = ev.getPoint();
if(!firstclick)
{
ls.start_x = (int)p.getX();
ls.start_y = (int)p.getY();
firstclick = true;
System.out.println("first click detected");
}
else
{
ls.end_x = (int)p.getX();
ls.end_y = (int)p.getY();
firstclick = false;
System.out.println("second click detected");
repaint();
}
}
public void mousePressed(MouseEvent ev)
{
}
public void mouseReleased(MouseEvent ev)
{
}
public void mouseEntered(MouseEvent ev)
{
}
public void mouseExited(MouseEvent ev)
{
}
}
//--------------
//LineSegment class is here
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class LineSegment implements Shape
{
int start_x = 0;
int start_y = 0;
int end_x = 0;
int end_y = 0;
public void area()
{
}
public void draw(Graphics g)
{
g.setColor(Color.BLACK);
g.drawLine(start_x, start_y, end_x, end_y);
}
}
//---------------
//shape interface is here
import javax.swing.*;
import java.awt.*;
public interface Shape
{
public void area();
public void draw(Graphics g);
}
Now, the problem is the following:
first click:
point read (first click detected)
second click:
point read (second click detected)
line drawn
third click:
point read (first click detected)
point read (second click detected)
line drawn (a point as first and second click are the same)
fourth click:
point read (first click detected)
point read (second click detected)
line drawn (a point as first and second click are the same)
point read (first click detected)
point read (second click detected)
Basically, except for the first couple of clicks, I can't get a line to show for any two clicks.
Anyone knows what is going on?
thanks.