Adding a canvas to a panel doesn't show the canvas?

被刻印的时光 ゝ 提交于 2019-12-12 01:12:02

问题


First of all: sorry, if this question was asked before, but I cannot seem to find an answer anywhere, so here we go:

I am trying to get a canvas element to show while it being added to a panel with a titled border around the panel. Here is my code.

public class TestClass extends JFrame{

    private TestClass() {
        GuiCanvas canvas = new GuiCanvas();

        setTitle("TestClass");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(1300, 800);

        Border menuBorder = BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(Color.LIGHT_GRAY), "Overview");

        JPanel controlpanel = new JPanel();
        JPanel panelCanvas = new JPanel();

        panelCanvas.setBorder(menuBorder);
        panelCanvas.add(canvas);

        controlpanel.setLayout(new GridLayout(3, 1));
        controlpanel.add(panelCanvas);

        add(controlpanel);
        setLocationRelativeTo(null);
        setVisible(true);

        System.out.println(canvas.getBounds());

    }

    private class GuiCanvas extends Canvas {

        GuiCanvas() {
            setBackground(Color.LIGHT_GRAY);
        }

        @Override
        public void paint(Graphics g) {
            g.drawLine(20, 20, 20, 200);
        }
    }

    public static void main(String[] args) {
        new TestClass();
    }
}

The above code results in an empty panel with a titled border when it should show the defined line I draw in the GuiCanvas-Class. Am I missing something here? Is it even possible to add a canvas-element to a panel? Thanks for your help in advance :)


回答1:


It is indeed possible to add a Canvas object to a JPanel.

Your problem lies in the fact that your Canvas has no defined size. What you need are the two following lines

    canvas.setPreferredSize(new Dimension(1300,300));
    /*
     *
     */
    this.pack();

This will place your canvas inside the panelCanvas border, displaying a black vertical line on a light gray background.




回答2:


If you want the canvas to stretch to the size of the panel, change:

JPanel panelCanvas = new JPanel();

To:

JPanel panelCanvas = new JPanel(new GridLayout());

See also this answer:



来源:https://stackoverflow.com/questions/37207631/adding-a-canvas-to-a-panel-doesnt-show-the-canvas

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