简体   繁体   中英

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

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 :)

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM