I am using the netbeans builder "design" on a JFrame class. I have the traditional JFrame, I added into it (with the builder) a JPanel.
Now in the 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 don'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);
}
}
your class ImagePanel extends JPanel { must override getPreferredSize(),
because public void paintComponent(Graphics g) { (painting in Swing, Graphics(2D)) doesn't returns any size back to the container, simple returns Dimmension(0, 0)
JPanel has implemented FlowLayout (accepting only PreferredSize that came from its childs) in API, then your custom painting never will be visible on the screen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With