2012-10-18 64 views
0

我在关闭模式对话框后更新(或刷新)来自按钮的图标时出现问题。该图像基本上被JDialog的某些动作覆盖。如何从JButton/JLabel更新ImageIcon

这是我的代码:

conf = new Configurar(this, true,control);   
conf.setVisible(true); // Open dialog 
System.out.println("Cerrado"); // Check if is closed (debug) 
String logo =(String)config.get("logo"); // get path from image 
File newIcon =new File(logo); // Desesperate try 
ImageIcon img = new ImageIcon(newIcon.getAbsolutePath()); 
btn_main_image.setIcon(img); 
this.update(btn_main_image.getGraphics()); 
btn_main_image.updateUI(); // First Try 
this.repaint(); // Second Try 

第一次它工作正常,但是当我打开对话框并更改图像保持不变。

+0

在部署时,'logo'图像可能不是文件系统上的'File',而是Jar内的资源。如果是这样,它必须由'URL'访问。 –

回答

4
conf = new Configurar(this, true,control);   
conf.setVisible(true); // Some kind of file chooser ?? 
File newIcon =new File(logo); 
if (newIcon.exists()) { 
    ImageIcon img = new ImageIcon(newIcon.getAbsolutePath()); 
    btn_main_image.setIcon(img); 
    //this.update(btn_main_image.getGraphics()); // WHAT IS THIS?!?!?! 
    //btn_main_image.updateUI(); // NO NO NO, this has nothing to do with refreshing the graphics, it's L&F stuff 
    btn_main_image.invalidate(); 
    // Use this ONLY if invalidate doesn't work... 
    btn_main_image.revalidate(); 
    btn_main_image.repaint(); 
} 
+0

谢谢! ...但不起作用:c“setIcon”后的按钮具有相同的图像。 – rafuru

+0

请删除'OverlayLayout'所需的'btn_main_image.invalidate();'为'ImageIcon'使用flush()而不是'invalidate();' – mKorbel

+0

'ImageIcon'没有'flush'或'无效'方法? 'invalidate'可能会更好地在父级上调用,但这只会导致布局管理器被标记为无效。 'validate'可能是更好的选择 – MadProgrammer