为什么此代码有时只能工作(Java)

时间:2021-08-19 06:54:10

I don't quite get it, here's this code to produce a 3D cube:

我不太明白,这是生成3D立方体的代码:

import javax.media.j3d.*;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.vecmath.*;
import javax.swing.*;
import java.awt.event.*;

public class pject extends JFrame {
private Canvas3D canvas;
private SimpleUniverse uni;
private BranchGroup scene;


public pject() {
    this.setSize(600,400);
    this.addKeyListener(new KeyHandler());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
    this.add(canvas);

    uni = new SimpleUniverse(canvas);
    scene = new BranchGroup();
    start();
}
private void start() {
    ColorCube cc = new ColorCube(0.1d);
    scene.addChild(cc);
    Transform3D lookAt = new Transform3D();
    lookAt.lookAt(new Point3d(0.0, 0.0, 1.0), new Point3d(0.0, 0.0, 0.0), new Vector3d(0.0, 1.0, 0));
    lookAt.invert();
    uni.getViewingPlatform().getViewPlatformTransform().setTransform(lookAt);
    uni.addBranchGraph(scene);



}



public static void main(String[] args) {
    pject frame = new pject();
}

float x = 0.4f;     
private class KeyHandler extends KeyAdapter {
    public void keyPressed(KeyEvent e) {                       
        if (e.getKeyCode() == KeyEvent.VK_LEFT) x += 0.001;   

        Transform3D lookAtx = new Transform3D();
        lookAtx.lookAt(new Point3d(x, 0.0, 1.0), new Point3d(x, 0.0, 0.0), new Vector3d(0.0, 1.0, 0));
        lookAtx.invert();
        uni.getViewingPlatform().getViewPlatformTransform().setTransform(lookAtx);

    }
    public void keyReleased(KeyEvent e) {
    }     
}

 } 

It works, but sometimes. I compile it, it works. I make absolutely no changes at all, compile it, and it doesn't work. I then have to compile it 10-20 times until one of those compilations actually work.

它有效,但有时。我编译它,它的工作原理。我完全没有任何改变,编译它,它不起作用。然后我必须编译10-20次,直到其中一个编译实际工作。

When it doesn't work, it just shows a JFrame with no Canvas3D on it (or if there is one, it's not visible).

当它不起作用时,它只显示一个没有Canvas3D的JFrame(或者如果有的话,它是不可见的)。

This just doesn't make any sense to me. Why would my code only sometimes compile right? Why is it that compiling it over and over again 10-20 eventually will show me my cube?

这对我没有任何意义。为什么我的代码有时只编译正确?为什么一遍又一遍地编译它10-20最终会告诉我我的立方体?

1 个解决方案

#1


0  

Call this.setVisible(true); at the end of the constructor.

调用this.setVisible(true);在构造函数的末尾。

#1


0  

Call this.setVisible(true); at the end of the constructor.

调用this.setVisible(true);在构造函数的末尾。