Search This Blog

Wednesday, 2 September 2015

Paint Crosshair line drawing tool in Java

package rehan;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;

import javax.swing.JFrame;

public class DefPoly extends JFrame{

ArrayList<Point> pointsArrayList = new ArrayList<Point>();

public DefPoly(){
setVisible(true);
setSize(500,500);
addWindowListener(new WindowListener() {

@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent arg0) {
System.exit(0);

}

@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub

}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt){
pointsArrayList.add( evt.getPoint() );
repaint();
}
});
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}

public static void main(String[] args) {
new DefPoly();
}

public void paint(Graphics g){
g.setColor(Color.white);
if (pointsArrayList.size()>=2){
for (int i = 0; i<pointsArrayList.size()-1; i++){
Point p1 = pointsArrayList.get(i);
Point p2 = pointsArrayList.get(i+1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
}

}

No comments:

Post a Comment