Canvas3D not appearing in Swing window

馋奶兔 提交于 2019-12-08 05:23:03

问题


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.


回答1:


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());



回答2:


Canvas3D needs a size passed to it; setting the preferred configuration from SimpleUniverse is not enough. In my case, that meant this code:

        // 3D canvas initialization
        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();
        canvas.setSize(100, 100);
        canvasPanel.add(canvas);


来源:https://stackoverflow.com/questions/210998/canvas3d-not-appearing-in-swing-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!