import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Jooned3 extends Applet implements MouseListener, MouseMotionListener{ Vector hoidla=new Vector(); int algx, algy; int otsx, otsy; static final int puutekaugus=10; Graphics gr; public Jooned3(){ addMouseListener(this); addMouseMotionListener(this); } public void mousePressed(MouseEvent e){ algx=e.getX(); algy=e.getY(); otsx=algx; otsy=algy; gr=getGraphics(); gr.drawLine(algx, algy, otsx, otsy); gr.setXORMode(Color.white); } public void mouseReleased(MouseEvent e){ hoidla.addElement(new Joon(algx, algy, e.getX(), e.getY())); repaint(); } public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){} public void mouseDragged(MouseEvent e){ gr.drawLine(algx, algy, otsx, otsy); otsx=e.getX(); otsy=e.getY(); gr.drawLine(algx, algy, otsx, otsy); } public void mouseMoved(MouseEvent me){ Enumeration e=hoidla.elements(); Graphics g=getGraphics(); while(e.hasMoreElements()){ Joon j=(Joon)e.nextElement(); if(punktiKaugusJoonest(me.getX(), me.getY(), j.x1, j.y1, j.x2, j.y2)>puutekaugus){ g.setColor(Color.black); } else { g.setColor(Color.yellow); } g.drawLine(j.x1, j.y1, j.x2, j.y2); } } public void paint(Graphics g){ Enumeration e=hoidla.elements(); while(e.hasMoreElements()){ Joon j=(Joon)e.nextElement(); g.drawLine(j.x1, j.y1, j.x2, j.y2); } } static double punktiKaugusJoonest(int px, int py, int x1, int y1, int x2, int y2){ //nihutan joone algama algpunktist, kõigest lahutan joone esimese punkti asukoha. px-=x1; py-=y1; x2-=x1; y2-=y1; //jäi järele joon punktist 0, 0; x2, y2 //Joone võrrand: y=(y2/x2)*x ehk (y2/x2)*x-y=0 //kui x2==0, siis joon vertikaalne, kaugus joonest == |px| //Muul juhul avaldatakse kaugus valemist // a(px)+b(py)/sqrt(a*a+b*b) // if(x2==0){return (px>0)?px:-px;} double a=y2/(double)x2; double b=-1; double vastus= Math.abs((a*px+b*py)/Math.sqrt(a*a+b*b)); return vastus; } public static void main(String[] arg){ Frame f=new Frame(); f.add(new Jooned3()); f.setSize(300, 300); f.setVisible(true); } class Joon{ int x1, y1, x2, y2; Joon(int ux1, int uy1, int ux2, int uy2){ x1=ux1; y1=uy1; x2=ux2; y2=uy2; } } }