如何从JButton / JLabel更新ImageIcon

时间:2012-10-18 22:06:28

标签: java image swing jlabel imageicon

关闭模式对话框后,我在按钮上更新(或刷新)图标时遇到问题。图像基本上被JDialog的某些操作覆盖。

这是我的代码:

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

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

1 个答案:

答案 0 :(得分: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();
}