/*<applet code=lc height=1000 width=1000>
</applet>
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <applet code=lineclip height=600 width=600>
</applet>*/
public class lineclip extends Applet implements MouseListener, MouseMotionListener, ActionListener
{
Button bClip=new Button("Clip");
Graphics key;
float x,y,xa,ya,xb,yb,dx,dy,m,p,xEnd;
public void init()
{
add(bClip);
bClip.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void mouseClicked(MouseEvent me){}
public void mouseMoved(MouseEvent me){}
public void mouseDragged(MouseEvent me){}
public void mousePressed(MouseEvent me)
{
xa=me.getX();
ya=me.getY();
}
public void mouseReleased(MouseEvent me)
{
xb=me.getX();
yb=me.getY();
repaint();
}
public void paint(Graphics g)
{
g.drawRect(200,200,200,200);
g.drawLine(Math.round(xa),Math.round(ya),Math.round(xb),Math.round(yb));
}
public void actionPerformed(ActionEvent ae)
{
key=getGraphics();
key.setColor(Color.white);
key.drawLine(Math.round(xa),Math.round(ya),Math.round(xb),Math.round(yb));
key.setColor(Color.black);
dx=Math.abs(xa-xb);
dy=Math.abs(ya-yb);
if (dx==0)
m=2;
else
m=(yb-ya)/(xb-xa);
if (m>=0 && m<=1)
{
p=2*dy-dx;
if (xa>xb)
{ x=xb;y=yb;xEnd=xa; }
else
{ x=xa;y=ya;xEnd=xb; }
//plot_clip(key);
while (x<xEnd)
{
x=x+1;
if (p<0)
p=p+2*dy;
else
{ y=y+1;p=p+2*(dy-dx); }
plot_clip(key);
}
}
if (m>=1)
{
p=2*dx-dy;
if (ya>yb)
{ x=xb;y=yb;xEnd=ya; }
else
{ x=xa;y=ya;xEnd=yb; }
//plot_clip(key);
while (y<xEnd)
{
y=y+1;
if (p<0)
p=p+2*dx;
else
{x=x+1;p=p+2*(dx-dy);}
plot_clip(key);
}
}
if (m<0 && m>=-1)
{
p=2*dy-dx;
if (xa<xb)
{ x=xb;y=yb;xEnd=xa; }
else
{ x=xa;y=ya;xEnd=xb; }
//plot_clip(key);
while (x>xEnd)
{
x=x-1;
if (p<0)
p=p+2*dy;
else
{ y=y+1;p=p+2*(dy-dx); }
plot_clip(key);
}
}
if (m<-1)
{
p=2*dx-dy;
if (ya<yb)
{ x=xb;y=yb;xEnd=ya; }
else
{ x=xa;y=ya;xEnd=yb; }
//plot_clip(key);
while (y>xEnd)
{
y=y-1;
if (p<0)
p=p+2*dx;
else
{ x=x+1;p=p+2*(dx-dy); }
plot_clip(key);
}
}
}
public void plot_clip(Graphics key)
{
if (x<200 || x>400 || y<200 || y>400)
key.setColor(Color.white);
else
key.setColor(Color.black);
key.drawString(".",Math.round(x),Math.round(y));
}
}
No comments:
Post a Comment