2013-03-13 51 views
0

当数据提交给数据库时,我需要重新加载JPanel的背景图像。 我创建了从数据库填充图像的JPanel。当我更新图像并提交时,背景会自动更改。 我也尝试使用repaint()和revalidate(),但它不会工作。 它必须重新启动应用程序并再次运行,它的工作原理。如何刷新/重新加载JPanel中的图像

这是我在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); 
} 

这是我的助手类:

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(); 
    } 
} 

任何解决方案?感谢您的关注:)

回答

2

首先,你的助手类应该设置它自己的大小。

其次,您应该只使用JPanelGraphics实例。

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); 
    } 
} 

现在你的电话会看起来像这样。

public void getLogo(Company company, PanelCompany view) { 
     JPanel panel = new BackgroundImage(company.getLogoBlob()); 
     view.getPanelPhoto().add(panel); 
} 

PanelCompany必须使用布局管理器。这里是Oracle's Visual Guide to Layout Managers

挑一个。

+0

@GilbertLeBlanc:考虑重载'getPreferredSize',建议[这里](http://stackoverflow.com/q/7229226/230513) – trashgod 2013-03-30 12:46:48