日期:2014-05-20  浏览次数:20708 次

JAVA3D编写添加鼠标行为的时候出现下面的错误
--------------------Configuration:   <Default> --------------------
Exception   in   thread   "main "   javax.media.j3d.MultipleParentException:   Group.addChild:   child   already   has   a   parent
        at   javax.media.j3d.GroupRetained.checkValidChild(GroupRetained.java:452)
        at   javax.media.j3d.GroupRetained.addChild(GroupRetained.java:461)
        at   javax.media.j3d.Group.addChild(Group.java:271)
        at   objLoader.createSceneGraph(objLoader.java:122)
        at   objLoader. <init> (objLoader.java:164)
        at   objLoader.main(objLoader.java:173)

------解决方案--------------------
异常不是已经说得很清楚了吗?一个child只能有一个parent。

------解决方案--------------------
在准备导入里 objTrans2.addChild(objTrans2); 不要,还有就是你把鼠标事件加错Transfrom3D了,要添加鼠标事件先要删掉旋转的代码
我将可运行的代码发在这


import com.sun.j3d.loaders.objectfile.ObjectFile;
import com.sun.j3d.loaders.ParsingErrorException;
import com.sun.j3d.loaders.IncorrectFormatException;
import com.sun.j3d.loaders.Scene;
import java.awt.GraphicsConfiguration;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.*;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.behaviors.mouse.*;
import com.sun.j3d.utils.image.*;
import java.io.*;
import javax.imageio.*;
import javax.media.j3d.*;
import javax.vecmath.*;

public class objLoader extends Applet {
public BranchGroup createSceneGraph(String filename) {

BranchGroup objRoot = new BranchGroup();

BoundingSphere bounds =new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);//设置涉及范围

{
Color3f bgColor = new Color3f(0.2f, 0.3f, 0.8f);//背景颜色
Background bg = new Background(bgColor);
bg.setApplicationBounds(bounds);
objRoot.addChild(bg);
}
{
//设置变换组
TransformGroup objTrans1=new TransformGroup();

Transform3D x = new Transform3D();
Transform3D y = new Transform3D();


TransformGroup xRot=new TransformGroup();

xRot.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
xRot.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);


x.rotX(Math.PI/180); //x轴旋转
xRot.setTransform(x);
objRoot.addChild(xRot);
y.rotY(Math.PI/180);

objTrans1.setTransform(y); //Y轴旋转
objTrans1.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objTrans1.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);

xRot.addChild(objTrans1);

//定义鼠标行为
// MouseRotate behavior = new MouseRotate();
// behavior.setTransformGroup(objTrans1);
// objRoot.addChild(behavior);
// behavior.setSchedulingBounds(bounds);

// MouseZoom behavior2 = new MouseZoom();
// behavior2.setTransformGroup(objTrans1);
// objRoot.addChild(behavior2);
// behavior2.setSchedulingBounds(bounds);

// MouseTranslate behavior3 = new MouseTranslate();
// behavior3.setTransformGroup(objTrans1);
// objRoot.addChild(behavior3);
// behavior3.setSchedulingBounds(bounds);
}


{


//整体光设置