在你的程序里面起一个线程,它会一直要求得到焦点,这样你就可以随时退出了
import java.awt.*;
import java.awt.event.*;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.image.*;
import com.sun.j3d.utils.behaviors.mouse.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import javax.swing.JFrame;
public class tuxiang extends JFrame implements KeyListener,
Runnable {
private volatile boolean isRunning;
private ScreenManager screen;
private DisplayMode displayMode=new DisplayMode(800,600,16,0);
public void init() {
screen=new ScreenManager();
screen.setFullScreen(displayMode,this);
this.addKeyListener(this);
this.requestFocusInWindow();
isRunning=true;
new Thread(this).start();
}
public void run(){
while(true){
try{
Thread.sleep(100);
this.requestFocusInWindow();
}
catch(Exception exe){
exe.printStackTrace();
}
}
}
public void stop() {
isRunning=false;
System.exit(0);
}
public void loop() {
int i=0;
while(isRunning) {
i++;
System.out.println("执行了"+i+"秒");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ESCAPE) {
stop();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public BranchGroup createSceneGraph() {
BranchGroup objroot=new BranchGroup();
BoundingSphere bounds=new BoundingSphere(new Point3d(0.0,.0,.0),100.0);
Background bg=new Background(new Color3f(1.f,1.f,1.f));
bg.setApplicationBounds(bounds);
objroot.addChild(bg);
TransformGroup objTrans=new TransformGroup();
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objroot.addChild(objTrans);
DirectionalLight light=new DirectionalLight(
new Color3f(1.f,1.f,0.f),new Vector3f(0.f,1.f,-1.f));
light.setInfluencingBounds(bounds);
objroot.addChild(light);
Appearance ap=new Appearance();
Material mat=new Material();
mat.setDiffuseColor(new Color3f(3.f,2.f,1.f));
ap.setMaterial(mat);
objTrans.addChild(new Box(.2f,.2f,.2f,ap));
MouseRotate b=new MouseRotate();
b.setSchedulingBounds(bounds);
b.setTransformGroup(objTrans);
objroot.addChild(b);
objroot.compile();
return objroot;
}
public void run(DisplayMode displayMode) {
new Thread(new Runnable(){
public void run(){
try {
init();
loop();
} finally {
screen.restoreScreen();
}
}
}).start();
}
public tuxiang() {
setLayout(new BorderLayout());
Canvas3D c=new Canvas3D(SimpleUniverse.getPreferredConfiguration());
add("Center",c);
SimpleUniverse u=new SimpleUniverse(c);
u.getViewingPlatform().setNominalViewingTransform();
BranchGroup scene=createSceneGraph();
u.addBranchGraph(scene);
}
public static void main(String arg[]) {
DisplayMode displayMode=new DisplayMode(
800,600,32,DisplayMode.REFRESH_RATE_UNKNOWN);
tuxiang t=new tuxiang();
t.run(displayMode);
}
}
红色的地方是加的部份,其它部份不用变