1. 程式人生 > >掌握Applet 類與Applet小程式的基本結構,能夠編寫Applet小程式;

掌握Applet 類與Applet小程式的基本結構,能夠編寫Applet小程式;

編寫Applet程式在畫出一條兩個週期的正弦曲線,要求:
1)畫出座標系,座標系在applet視窗的中央,作圖區域的大小通過html檔案傳遞
2)曲線的顏色為紅色,座標系為綠色,有刻度


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet;
public class SinGraphic extends JApplet{
final int N=1000;
public void init(){
int W,H;
W=Integer.parseInt(getParameter("width"));//獲取高度
H=Integer.parseInt(getParameter("height"));//獲取寬度
double EX=(W-80)/(4*Math.PI);
double EY=(H-80)/2.0;//放大倍數
}
public void paint(Graphics g){
int W=getSize().width;
int H=getSize().height;
double h=4*Math.PI/N;//步長
double x1=-2*Math.PI,y1=Math.sin(x1),x2,y2;
double EX=(W-80)/(4*Math.PI);
double EY=(H-80)/2.0;
int intx,inty,i=0;
//先畫座標系
String[] ax={"-2pi","-3pi/2","-pi","-pi/2","0","pi/2","3pi/2","2pi"};
String[] ay={"-1","-0.8","-0.6","-0.4","-0.2","0","0.2","0.4","0.6","0.8","1"};
g.setColor(Color.green);
Graphics2D g_2d=(Graphics2D)g;
g_2d.setStroke(new BasicStroke(4f));//畫筆加粗
Font font=new Font("宋體",Font.BOLD,10);
g.setFont(font);
//x軸
g.drawLine(0,H/2,W-20,H/2);
g.drawLine(W-30,H/2-5,W-20,H/2);
g.drawLine(W-30,H/2+5,W-20,H/2);
//x軸刻度
intx=(int)(x1+h);
inty=H/2;
if(i<8){
g.setColor(Color.green);
g.drawLine(intx,inty,intx,inty+10);
g.setColor(Color.black);
g.drawString(ax[i++],intx,inty+10);
x1=x2;
y1=y2;
//y軸
g.setColor(Color.green);
g.drawLine(W/2,0,W/2,H);
g.drawLine(W/2,0,W/2-5,20);
g.drawLine(W/2,0,W/2+5,20);
while(i<11){
x2=x1+h;
y2=Math.sin(x2);
intx=W/2;
inty=(int)(-y2*EY+H/2+10);
g.setColor(Color.green);
g.drawLine(intx,inty,intx+10,inty);
g.setColor(Color.black);
g.drawString(ay[i++],intx+10,inty);
}
//畫曲線
g.setColor(Color.red);
for(i=0;i<N;i++){
x2=x1+h;
y2=Math.sin(x2);
g.drawLine((int)(x1*EX)+W/2,-(int)(y1*EY)+H/2,(int)(x2*EX)+W/2,-(int)(y2*EY)+H/2);
x1=x2;
y1=y2;
}
}
}

這裡寫圖片描述