Hey all!
I use the folowing class in my program to draw lines. However I also need to be able to delete them. So I need to add a mouselistener to the lines but I don't know how and whereto do this.. Can anybody help me with this?
Thanks!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
public class Drawing extends JComponent implements MouseListener, MouseMotionListener
{
// public JPanel [] lines = new JPanel [50];
public Drawing()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
for (int i = 0; i < count; i++)
g.drawLine(ptStarts[i].x, ptStarts[i].y, ptEnds[i].x, ptEnds[i].y);
}
// MouseListener
public void mousePressed(MouseEvent e)
{
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0)
{
if (count < 50)
{
drawing = true;
start.setLocation(e.getX(), e.getY());
end.setLocation(start);
Graphics g = getGraphics();
g.setXORMode(getBackground());
g.drawLine(start.x, start.y, end.x, end.y);
g.dispose();
// setName("" + 100 + i);
}
else
{
JOptionPane.showMessageDialog(this, "Only 50 lines can be drawn!", "No more", JOptionPane.ERROR_MESSAGE);
}
}
else if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0)
{
count = 0;
repaint();
}
}
public void mouseReleased(MouseEvent e)
{
if (drawing)
{
drawing = false;
if (!start.equals(end))
{
ptStarts[count] = new Point(start);
ptEnds[count] = new Point(end);
count++;
repaint();
}
}
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {}
// MouseMotionListener
public void mouseDragged(MouseEvent e)
{
if (drawing)
{
Graphics g = getGraphics();
g.setXORMode(getBackground());
g.drawLine(start.x, start.y, end.x, end.y);
end.setLocation(e.getX(), e.getY());
g.drawLine(start.x, start.y, end.x, end.y);
g.dispose();
}
}
public void mouseMoved(MouseEvent e) {}
// protected member variables
protected int count = 0;
protected Point[] ptStarts = new Point[50];
protected Point[] ptEnds = new Point[50];
protected Point start = new Point(), end = new Point();
protected boolean drawing = false;
}