Search code examples
javaswingjava-3d

Canvas3D not appearing in Swing window


I am attempting to insert a Canvas3D object inside a Swing JPanel, but the code doesn't seem to be working (i.e. nothing happens):

        Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
        SimpleUniverse universe = new SimpleUniverse(canvas);
        BranchGroup root = new BranchGroup();
        root.addChild(new ColorCube());
        universe.addBranchGraph(root);
        universe.getViewingPlatform().setNominalViewingTransform();
        canvasPanel.add(canvas);

What am I missing? The JPanel was created using NetBean's Visual Editor.


Solution

  • Probably you have to set a layout manager on the panel, which automatically expands the child components to the full area. A JPanel has a FlowLayout by default, which does not expand the child components. You could try a BorderLayout instead by calling:

    canvasPanel.setLayout(new BorderLayout());