How to make a JPanel inside a JFrame fill the whole window?

后端 未结 4 452
深忆病人
深忆病人 2021-01-14 01:43

In the below example, how can I get the JPanel to take up all of the JFrame? I set the preferred size to 800x420 but it only actually fills 792x391.

import j         


        
4条回答
  •  萌比男神i
    2021-01-14 02:08

    If you are having only one panel in frame and nothing else then try this:

    • Set BorderLayout in frame.
    • Add panel in frame with BorderLayout.CENTER

    May be this is happening because of while loop in JPanel.(Not sure why? finding actual reason. Will update when find it.) If you replace it with paintComponent(g) method all works fine:

    public BSTest() {
        //--- your code as it is
        add(panel, BorderLayout.CENTER);
        //-- removed panel.drawStuff();
    }
    
    public class DrawPanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.BLACK);
            System.out.println("W:" + getSize().width + ", H:" + getSize().height);
            g2d.fillRect(0, 0, getSize().width, getSize().height);
        }
     }
    
    //your code as it is.
    

提交回复
热议问题