Netbean Java Swing, JPanel/Jlabel Cant cover whole Frame

Here’s what I would do. Use a JPanel for the background and throw in some custom paint code.

  1. Drag a JPanel to the form and expand that to cover the whole frame, to be the background.

  2. Right click on the JPanel and select Customize Code from the context menu. You will see the following dialog. You can now edit the code.

    enter image description here

  3. Make sure to select custom creation from the drop down and type this

    jPanel1 = new JPanel() {
        BufferedImage img;
        {
            try {
                img = ImageIO.read(getClass().getResource("/resources/stackoverflow5.png"));
            } catch (IOException ex) {  ex.printStackTrace(); }
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    
        }
    };
    
  4. You probably will have to resolve imports. Just hit Ctrl + Shift + I

  5. Also you will have to change the path of the image to your path.

Here’s my file structure

enter image description here

And here’s the result

enter image description here

Leave a Comment