Paint background of JPanel

前端 未结 5 684
盖世英雄少女心
盖世英雄少女心 2021-01-19 05:16

How can I tell the paint method to draw background on JPanel only and not on the entire JFrame. My JFrame size is bigger than the JPanel. When I try to paint a grid backgrou

5条回答
  •  自闭症患者
    2021-01-19 05:30

    The code you posted is not complete, it's missing how the panel is added to the JFrame and which LayoutManager is being used.
    The code seams to be correct. Are you sure the JPanel is not occupying the whole JFrame? Add a System.out.println(drawingPanel.getSize()) to check this.
    If you are using the BorderLayout, the default for JFrame, and has just added the panel without any constraint, the panel will use the whole area. The PreferredSize is ignored.
    Try this, just for testing:

    public Drawing (){
        drawingPanel = new JPanel();
        drawingPanel.setPreferredSize(new Dimension(600,600));  // ignored
        drawingPanel.setBounds(0, 0, 600, 600);  // location and size
        setLayout(null);
        add(drawingPanel);
    }
    

    but IMO this is not the best or correct way to do it. I would prefer to override the paintComponent() method from the JPanel, as suggested by Thorsten and camickr.
    But it will still use the whole area of the JFrame until other Component is added to the JFrame or the LayoutManager changed.

提交回复
热议问题