Reputation: 1738
I need to reload the JPanel's background image, when data submitted to Database. I create JPanel that populate image from Database. And when i updated the image, and submit it, the background automatically change. I also try to use repaint() and revalidate() but it wont work. It must to restart application and run again, it works.
This is my code to display background in JPanel.
public void getLogo(Company company, PanelCompany view) {
JPanel panel = new BackgroundImage(company.getLogoBlob());
panel.revalidate();
panel.setVisible(true);
panel.setBounds(10, 10, 120, 120);
view.getPanelPhoto().add(panel);
}
This my helper class :
public class BackgroundImage extends JPanel{
private Image image;
public BackgroundImage (InputStream input) {
try {
image = ImageIO.read(input);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D gd = (Graphics2D) grphcs.create();
gd.drawImage(image, 0, 0, getWidth(), getHeight(), this);
gd.dispose();
}
}
Any solutions? Thanks for your attention before :)
Upvotes: 0
Views: 4771
Reputation: 51445
First, your helper class should set it's own size.
Second, you should just use the Graphics
instance of the JPanel
.
public class BackgroundImage extends JPanel{
private Image image;
public BackgroundImage (InputStream input) {
try {
image = ImageIO.read(input);
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
Now your call would look like this.
public void getLogo(Company company, PanelCompany view) {
JPanel panel = new BackgroundImage(company.getLogoBlob());
view.getPanelPhoto().add(panel);
}
Your PanelCompany
class must use a layout manager. Here's Oracle's Visual Guide to Layout Managers.
Pick one.
Upvotes: 2