Background image not showing in Swing Netbeans builder

I am using the netbeans "design" in the JFrame class. I have a traditional JFrame, I added (with creator) a JPanel to it.

Now in code, I want to add a background to this panel like this:

public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
        initComponents();
        addBackground();
    }

    private void addBackground()
    {
        Image bgImage;
        try {
            bgImage = ImageIO.read(new File("src/general/Mockup.png"));
            jPanel1.add(new NewJFrame.ImagePanel(bgImage));
            jPanel1.repaint();
        } catch (IOException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
}

      

I can't see anything, just an empty JFrame / JPanel.

Btw I am using this for the ImagePanel code

@SuppressWarnings("serial")
class ImagePanel extends JPanel {
    private Image image;

    ImagePanel(Image image) {
        this.image = image;
    };

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
}

      

+3


source to share


3 answers




+5


source


What is jPanel1? What layout is he using? How big is the ImagePanel object after rendering the GUI? Instead of going through all this gymnastics, why not just use a JLabel with an image (or an ImagePanel instance) as your JFrame contentPane? Please note that this type of encoding is one of the reasons I avoid using the NetBeans generated code. Let me write the code myself and I can have complete control over everything my GUI does and shows.



+3


source


Why don't you just add the JLabel and paste the image name into the constructor? How:

JFrame background = new JFrame ("back.png");

Then you can add this label directly to the frame or JPanel.

+1


source







All Articles