Java 实现中点法画线

 

Java 实现中点法画线_第1张图片

用重点画线法画直线,当然其实这直线应该是弯曲的,应为这个点太大了所以看着像是直线,我同学他们用来演示的都不是这么直的。其中,paintComponent (Graphics line)这个方法很重要。貌似在swing组件中,都继承了一个接口paint,所以这个不算是自己定义的函数,是一个接口的实现。

 

代码如下:

画图实现程序:

LinePanel.java

import java.awt.*;
import java.awt.event.*;
import java.lang.Math.*;
import javax.swing.*;

public class LinePanel extends JPanel implements MouseListener,MouseMotionListener
{
  private Point point1=null,point2=null;
 private int flag=0;
  public LinePanel()
  {
   super();
   addMouseListener(this);
   addMouseMotionListener(this);
   setBackground(Color.white);
   setPreferredSize(new Dimension(800,600));
   repaint();
  
  }
  public void paintComponent (Graphics line){
  // super.paintComponent(line);
   line.setColor(Color.WHITE);
   line.drawRect(0, 0, getWidth(), getHeight());
   // super();
 
   paintLine( line);
  }
  public void paintLine(Graphics line)
  {
   super.paintComponents(line);
   line.setColor(Color.red);

  
   if((point1!=null)&&(point2!=null))
   {   String str1,str2;
    str1=point1.getX()+","+point1.getY();
    line.drawString(str1, point1.x, point1.y);
    str2=point2.getX()+","+point2.getY();
    line.drawString(str2, point2.x, point2.y);
   
   //line.drawLine(point1.x, point1.y, point2.x,point2.y);
    DDA(line,point1,point2);
   }
  }//paint ends
 
  //DDA
  public void DDA(Graphics line,Point point1,Point point2)
  {
  int x1,y1,x2,y2;
  int dx,dy,epsl,k;
  float x,y,xIncre,yIncre;
 
  x1=point1.x;
  y1=point1.y;
  x2=point2.x;
  y2=point2.y;
 
  dx=x2-x1; 
  dy=y2-y1;
  x=x1; 
  y=y1;
  if(Math.abs(dx)>Math.abs(dy))
   epsl=Math.abs(dx);
  else
   epsl=Math.abs(dy);
  xIncre =(float)dx/(float)epsl;
  yIncre =(float)dy/(float)epsl;
 
  for(k=0;k<=epsl;k++)
  {
   line.fillOval((int)(x+0.5),(int)(y+0.5),3,3);
   x=x+xIncre;
   y=y+yIncre;
  }
 
  }//DDA ends
 
  //实现监听器接口
    public void mousePressed(MouseEvent e)
   {   

  
 }
 public void mouseDragged(MouseEvent event){}
 public void mouseClicked(MouseEvent event)
 {   flag++;
  if(flag%2==0){
  point1=event.getPoint();
  repaint();
  }
  else
   point2=event.getPoint();
  //repaint();
 }
 public void mouseReleased(MouseEvent event)
 {
  point2=event.getPoint();
  
        repaint();
 }
 public void mouseEntered(MouseEvent event){}
 public void mouseExited(MouseEvent event){}
 
 public void mouseMoved(MouseEvent event)
 {
            
  point2=event.getPoint();   
  //repaint();
  }
 
 
}

 

一个驱动程序,

Line.java

import javax.swing.*;

public class Line
{
  public Line()
  {
  
  }
 
  public static void main(String args[])
  {
   JFrame frame =new JFrame("软件0804邓超 画线程序");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   LinePanel panel =new LinePanel();
   frame.getContentPane().add(panel);
   frame.pack();
   frame.setVisible(true);
  
  }

}

 

 

你可能感兴趣的:(java,float,import,swing,null,string)