- This is a 3D viewer in which a cube and the 3 axes can be seen. The view can be rotated by the 3 x,y and z sliders.
- Paste the following code:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Three_djar {
@SuppressWarnings("serial")
public static void main(String[] args) throws InterruptedException {
//Dynamic
final int s=300;
//Statics
final
JFrame frm=new JFrame("3DViewer");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setSize(s+15+210, s+39);
frm.setLayout(null);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final double[][][] a=new double[s][s][s];
for(int i=100;i<200;i++) {
a[100][100][i]=1;
a[200][100][i]=1;
a[100][200][i]=1;
a[200][200][i]=1;
a[100][i][100]=1;
a[200][i][100]=1;
a[100][i][200]=1;
a[200][i][200]=1;
a[i][100][100]=1;
a[i][200][100]=1;
a[i][100][200]=1;
a[i][200][200]=1;
}
for(int i=0;i<s;i++) {
a[s/2][s/2][i]=1;
a[i][s/2][s/2]=1;
a[s/2][i][s/2]=1;
}
final
JSlider xf=new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
final
JSlider yf=new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
final
JSlider zf=new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
xf.setSize(200,20);
yf.setSize(200,20);
zf.setSize(200,20);
xf.setLocation(s+5,5);
yf.setLocation(s+5,25);
zf.setLocation(s+5,45);
frm.add(xf);frm.add(yf);frm.add(zf);
final
JPanel pnl[]= {new JPanel()};
ChangeListener ad=new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
frm.remove(pnl[0]);
final double xth=Math.toRadians(xf.getValue());
final double yth=Math.toRadians(yf.getValue());
final double zth=Math.toRadians(zf.getValue());
pnl[0]=new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.black);
for(int i=0;i<s;i++) {
for(int j=0;j<s;j++) {
for(int k=0;k<s;k++) {
if (a[i][j][k]==1) {
double x=i-s/2;
double y=j-s/2;
double z=k-s/2;
//X-Yaw
double ytemp=y;
y=Math.cos(xth)*y-Math.sin(xth)*z;
z=Math.cos(xth)*z+Math.sin(xth)*ytemp;
//Y-Pitch
double xtemp=x;
x=x*Math.cos(yth)+z*Math.sin(yth);
z=z*Math.cos(yth)-xtemp*Math.sin(yth);
//Z-Roll
xtemp=x;
x=Math.cos(zth)*x-Math.sin(zth)*y;
y=Math.sin(zth)*xtemp+Math.cos(zth)*y;
g.setColor(new Color(0,0,0,0.2f));
g.fillRect((int) (x+s/2), (int) (y+s/2), 2, 2);
}
}
}
}
}
};
pnl[0].setSize(s,s);
frm.add(pnl[0]);
frm.invalidate();
frm.validate();
frm.repaint();
}
};
xf.addChangeListener(ad);
yf.addChangeListener(ad);
zf.addChangeListener(ad);
frm.setVisible(true);
}
}
- Run this code.
No comments:
Post a Comment