import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* <p>Title: 正方體框圖</p>
* <p>Description: 繪制一個邊框的正方體,獲取鼠標事件根據鼠標的位置旋轉方體。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: Gr3d1m.java</p>
* @version 1.0
*/
public class Gr3d1m extends JFrame
implements MouseListener,MouseMotionListener {
int doX,doY;
int angX=30,angY=30;
Cube data = new Cube();
Color [] Col={Color.gray,Color.cyan,Color.green,
Color.red,Color.white,Color.orange,
Color.magenta,Color.pink};
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] args){
Gr3d1m G3 = new Gr3d1m();
}
/**
*<br>方法說明:構造器
*<br>輸入參數:
*<br>返回類型:
*/
public Gr3d1m() {
setTitle("3D cube Frame");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
setBackground(new Color(128,128,255));
setSize(350,350);
show();
}
/**
*<br>方法說明:鼠標按下事件,獲取鼠標位置
*<br>輸入參數:
*<br>返回類型:
*/
public void mousePressed(MouseEvent e) {
doX=e.getX();
doY=e.getY();
}
/**
*<br>方法說明:鼠標托拽事件,改變鼠標位置,重畫屏幕
*<br>輸入參數:
*<br>返回類型:
*/
public void mouseDragged(MouseEvent e) {
angX=angX+e.getY()-doY;
angY=angY+e.getX()-doX;
doX=e.getX(); doY=e.getY();
repaint();
}
/* 以下是實現MouseListener和MouseMotionListener必須重載的方法*/
public void mouseReleased(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
/**
*<br>方法說明:繪制圖形
*<br>輸入參數:
*<br>返回類型:
*/
public void paint( Graphics g ) {
delDeaw(g);
for (int i=0; i<data.x.length; i++) {
drawPG(g, data.x[i], data.y[i], data.z[i],
150,150,Col[i]);
}
g.setColor(Color.yellow);
g.drawString("X="+angX%360+" Y="+angY%360,
10,getSize().height-30);
}
/**
*<br>方法說明:擦拭屏幕,使用背景色覆蓋原來的圖形
*<br>輸入參數:
*<br>返回類型:
*/
public void delDeaw(Graphics g){
Insets insets = getInsets();
int L0 = insets.left, T0 = insets.top;
g.setColor(new Color(128,128,255));
g.fillRect(L0,T0,L0+350,T0+350);
}
/**
*<br>方法說明:繪制方體
*<br>輸入參數:
*<br>返回類型:
*/
public void drawPG(Graphics g,double []x,double []y,
double []z,int xp,int yp,Color co) {
double x1,y1,z0;
int len=x.length;
int [] xx=new int [len];
int [] yy=new int [len];
final double RAD=Math.PI/180.0;
double a=angX*RAD;
double b=angY*RAD;
double sinA=Math.sin(a),sinB=Math.sin(b);
double cosA=Math.cos(a),cosB=Math.cos(b);
for (int i=0; i<len; i++) {
x1= x[i]*cosB+z[i]*sinB;
z0=-x[i]*sinB+z[i]*cosB;
y1= y[i]*cosA- z0*sinA;
xx[i]=xp+(int)Math.rint(x1);
yy[i]=yp-(int)Math.rint(y1);
}
g.setColor(co);
g.drawPolygon(xx,yy,len);//繪制多邊形
}
}