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

后端 未结 4 420
深忆病人
深忆病人 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条回答
  • 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.
    
    0 讨论(0)
  • 2021-01-14 02:12

    Here's an alternative using pack instead.

    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class PackExample extends JFrame {
    
        public PackExample(){
            JPanel panel = new JPanel();
            panel.setPreferredSize(new Dimension(800,600));
            panel.setBackground(Color.green);
            add(panel);
            pack();
            setVisible(true);
       }
    
       public static void main(String[] args){
         new PackExample();
       }
    
    }
    
    0 讨论(0)
  • 2021-01-14 02:13

    This took me forever to figure out but its actually the simplest code ever. Just create a parent panel and pass GridLayout then add your child panel like this.

    JPanel parentPanel= new JPanel(new GridLyout());
    JPanel childPanel= new JPanel();
    parentPanel.add(childPanel);
    
    0 讨论(0)
  • 2021-01-14 02:28

    If you want to fill the JFrame with the whole of JPanel you need to setUndecorated to true i.e. frame.setUndecorated(true);. But now you have to worry about your MAXIMIZE< MINIMIZE, and CLOSE Buttons, towards the top right side(Windows Operating System)

    0 讨论(0)
提交回复
热议问题