2016-07-28 17 views
0

我正在Java中實現Line DDA算法。代碼看起來很好。Applet調整DDA算法在Java中的實現

我正面臨的問題是調整applet大小。小程序輸出很小,我希望它能夠以640-by-480的小程序窗口大小工作。
對於我已經使用resize(640,480);在paint()方法的開始,但它不起作用。它的作用是在小窗口(我認爲是350×200)上給出正確的輸出,然後將其自身擴大到640×480,程序不會終止(我必須強制退出程序) 。任何幫助,將不勝感激。我的實現代碼是:

package line; 

import java.applet.Applet; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.util.Scanner; 

public class DDALine extends Applet { 

    @Override 
    public void paint(Graphics g) {  
     //resize(640,480); 
     g.setColor(Color.RED); 

     float x,y,x1,y1,x2,y2,dx,dy,steps,incrx,incry; 
     int i; 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the value of x1 : "); 
     x1 = sc.nextInt(); 
     System.out.println("Enter the value of y1 : "); 
     y1 = sc.nextInt(); 
     System.out.println("Enter the value of x2 : "); 
     x2 = sc.nextInt(); 
     System.out.println("Enter the value of y1 : "); 
     y2 = sc.nextInt(); 

     dx = Math.abs(x2-x1); 
     dy = Math.abs(y2-y1); 

     if(dx>=dy) 
     steps=dx; 
     else 
     steps=dy; 

     incrx=dx/steps; 
     incry=dy/steps; 

     x=x1; 
     y=y1; 

     i=1; 

     while(i<=steps) { 
      g.drawLine(Math.round(x),Math.round(y),Math.round(x),Math.round(y)); 
      x=x+incrx; 
      y=y+incry; 
      i=i+1; 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException ex) { 
      } 
     } 
    } 
} 

回答

0

通過將init()方法中的setSize()方法解決。該代碼是:

import java.applet.Applet; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.util.Scanner; 

public class DDALine extends Applet { 


@Override 
public void init(){ 
    setSize(800, 600); 
} 

@Override 
public void paint(Graphics g) {  
g.setColor(Color.RED); 

float x,y,x1,y1,x2,y2,dx,dy,steps,incrx,incry; 
int i; 
Scanner sc = new Scanner(System.in); 
System.out.println("Enter the value of x1 : "); 
x1 = sc.nextInt(); 
System.out.println("Enter the value of y1 : "); 
y1 = sc.nextInt(); 
System.out.println("Enter the value of x2 : "); 
x2 = sc.nextInt(); 
System.out.println("Enter the value of y1 : "); 
y2 = sc.nextInt(); 

dx = Math.abs(x2-x1); 
dy = Math.abs(y2-y1); 

if(dx>=dy) 
steps=dx; 
else 
steps=dy; 

incrx=dx/steps; 
incry=dy/steps; 

x=x1; 
y=y1; 

i=1; 

    while(i<=steps) {   
      g.drawLine(Math.round(x), Math.round(y), Math.round(x), Math.round(y)); 
      x=x+incrx; 
      y=y+incry; 
      i=i+1; 
     try { 
      Thread.sleep(100); 
     } catch (Exception ex) { 
     } 
    } 
} 

}