Embedding a Java 3D SimpleUniverse object in a Swing Component

Java 3D objects are integrated in Swing components using Canvas3D as the bridge between the panel and the SimpleUniverse object.

While it is not difficult to integrate them together, it requires a little plumbing code to get it to show correctly on screen, so here is a minimal working example that anyone can use as a starting point in their Swing application.

I removed any unnecessary code and left the bare minimum that would display any arbitrary 3D object (a sphere in this case) on a JFrame window.

import java.awt.BorderLayout;
import javax.swing.JFrame;
public class JFrameWithCanvas3D extends JFrame {
public JFrameWithCanvas3D() {
super("Swing JFrame Wraps Canvas3D");
setLayout(new BorderLayout());
BallPanel panel = new BallPanel();
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
System.setProperty("sun.awt.noerasebackground", "true");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@SuppressWarnings("unused")
@Override
public void run() {
new JFrameWithCanvas3D();
}
});
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Transform3D;
import javax.swing.JPanel;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.universe.SimpleUniverse;
public class BallPanel extends JPanel {
public BallPanel() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 500));
add(makeCanvas());
}
private static Canvas3D makeCanvas() {
BranchGroup group = new BranchGroup();
group.addChild(makeLight());
group.addChild(new Sphere(5));
Canvas3D canvas3D = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
SimpleUniverse universe = new SimpleUniverse(canvas3D);
Transform3D viewTransform = new Transform3D();
viewTransform.setTranslation(new Vector3d(0, 0, 20)); //move "back" a little
universe.getViewingPlatform().getViewPlatformTransform().setTransform(viewTransform);
universe.addBranchGraph(group);
return canvas3D;
}
private static DirectionalLight makeLight() {
DirectionalLight light = new DirectionalLight(new Color3f(Color.WHITE), new Vector3f(-1.0f, -1.0f, -1.0f));
light.setInfluencingBounds(new BoundingSphere(new Point3d(0, 0, 0), 100));
return light;
}
}
view raw BallPanel hosted with ❤ by GitHub

Comments