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);
}
}
source to share
-
your class
ImagePanel extends JPanel {
should overridegetPreferredSize()
, -
because
public void paintComponent(Graphics g) {
(painting in Swing
,Graphics(2D)
) doesn't return any size back to the container, it just returnsDimmension(0, 0
) -
JPanel
injected (only accepts which came from its children) in the API then yours will never be visible on the screenFlowLayout
PreferredSize
custom painting
source to share
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.
source to share