问题
Consider a simple code:
import java.awt.*;
import javax.media.j3d.*;
import javax.vecmath.Color3f;
import javax.vecmath.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
public class Main {
public static void main(final String[] args) {
final SimpleUniverse universe = new SimpleUniverse();
final BranchGroup group = new BranchGroup();
TriangleArray triangle = new TriangleArray(3, TriangleArray.COORDINATES);
triangle.setCoordinates(0, new Point3f[]{
new Point3f(-0.3f, 0, -1),
new Point3f( 0, -0.3f, -1),
new Point3f( 0, 0, -1),
});
group.addChild(new Shape3D(triangle));
universe.addBranchGraph(group);
TriangleArray triangle1 = new TriangleArray(3, TriangleArray.COORDINATES);
triangle1.setCoordinates(0, new Point3f[]{
new Point3f(0.3f, 0, -1),
new Point3f( 0, 0.3f, -1),
new Point3f( 0, 0, -1),
});
group.addChild(new Shape3D(triangle1));
}
}
Before adding group
to the universe
, I add a triangle triangle
to it and it works fine.
After adding the group to the universe, I want to add another triangle triangle1
. However, I get the error
Exception in thread "main" javax.media.j3d.RestrictedAccessException: Group: only a BranchGroup node may be added
at javax.media.j3d.Group.addChild(Group.java:284)
at Main.<init>(Main.java:34)
at Main.main(Main.java:11)
So I set the BranchGroup
's ALLOW_DETACH
capability, remove it from the locale, add the object, then re-add the group to the universe:
// On initialization
group.setCapability(BranchGroup.ALLOW_DETACH);
// ...
// Adding another triangle
group.detach();
group.addChild(new Shape3D(triangle1));
universe.addBranchGraph(group);
However, that appears to be unnecessarily complex. Is there any other, better way to add the Object?
回答1:
Just call BranchGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND) very early and you should be allowed to add new children even after the BranchGroup is added.
来源:https://stackoverflow.com/questions/32423848/add-a-object-to-a-branchgroup-after-the-group-is-added-to-a-locale-or-a-simpleun