How to draw only straight line instead of angled one?
Dear friends,
I saw a very good code posted by guru here(I think is camickr),
But I tried to change it and I hope to draw only straight line instead of angled one, can you help how to do it?
Thanks so much.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
publicclass DrawingAreaextends JPanel
{
Vector angledLines;
Point startPoint =null;
Point endPoint =null;
Graphics g;
public DrawingArea()
{
angledLines =new Vector();
setPreferredSize(new Dimension(500,500));
MyMouseListener ml =new MyMouseListener();
addMouseListener(ml);
addMouseMotionListener(ml);
setBackground(Color.white);
}
publicvoid paintComponent(Graphics g)
{
// automatically called when repaint
super.paintComponent(g);
g.setColor(Color.black);
AngledLine line;
if (startPoint !=null && endPoint !=null)
{
// draw the current dragged line
g.drawLine(startPoint.x, startPoint.y, endPoint.x,endPoint.y);
}
for (Enumeration e = angledLines.elements(); e.hasMoreElements();)
{
// draw all the angled lines
line = (AngledLine)e.nextElement();
g.drawPolyline(line.xPoints, line.yPoints, line.n);
}
}
class MyMouseListenerextends MouseInputAdapter
{
publicvoid mousePressed(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
startPoint = e.getPoint();
}
}
publicvoid mouseReleased(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
if (startPoint !=null)
{
AngledLine line =new AngledLine(startPoint, e.getPoint(),true);
angledLines.add(line);
startPoint =null;
repaint();
}
}
}
publicvoid mouseDragged(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
if (startPoint !=null)
{
endPoint = e.getPoint();
repaint();
}
}
}
publicvoid mouseClicked( MouseEvent e )
{
if (g ==null)
g = getGraphics();
g.drawRect(10,10,20,20);
}
}
class AngledLine
{
// inner class for angled lines
publicint[] xPoints, yPoints;
publicint n = 3;
public AngledLine(Point startPoint, Point endPoint,boolean left)
{
xPoints =newint[n];
yPoints =newint[n];
xPoints[0] = startPoint.x;
xPoints[2] = endPoint.x;
yPoints[0] = startPoint.y;
yPoints[2] = endPoint.y;
if (left)
{
xPoints[1] = startPoint.x;
yPoints[1] = endPoint.y;
}
else
{
xPoints[1] = endPoint.x;
yPoints[1] = startPoint.y;
}
}
}
publicstaticvoid main(String[] args)
{
JFrame frame =new JFrame("Test angled lines");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
DrawingArea d =new DrawingArea();
frame.getContentPane().add( d );
frame.pack();
frame.setVisible(true);
}
}

