2013-01-04 18 views
0

請參考此錯誤:UIManager的改變顏色只有一次(靈氣)

4848910 : UIManager only updates colors once

我有一個JFrame兩個按鈕。從第一個按鈕,我改變LAF顏色由

UIManager.put("Button.background", new ColorUIResource(Color.red)); 
SwingUtilities.updateComponentTreeUI(this.getContentPane()); 

,並在第二個按鈕,我改變LAF色彩搭配

UIManager.put("Button.background", new ColorUIResource(Color.green)); 
SwingUtilities.updateComponentTreeUI(this.getContentPane()); 

這裏我使用將ColorUIResource(由錯誤的決議所述),但我問題與引用的錯誤中描述的相同。即UIManager會在第一次點擊任何按鈕時更改顏色,但在隨後的點擊中不會更改顏色。

我錯過了什麼嗎?任何幫助,將不勝感激。

回答

2

代碼

import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 
import javax.swing.JFrame; 
import javax.swing.LookAndFeel; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 
import javax.swing.UIDefaults; 
import javax.swing.UIManager; 
import javax.swing.UIManager.LookAndFeelInfo; 
import javax.swing.UnsupportedLookAndFeelException; 

public class NimbusTestButtonsBackground extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private javax.swing.JButton button; 

    public NimbusTestButtonsBackground() { 
     button = new javax.swing.JButton(); 
     button.setText("Text"); 
     add(button); 
     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
     this.pack(); 
     Timer t = new Timer(1000, new ActionListener() { 

      private Random r = new Random(); 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); 
       try { 
        LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance(); 
        UIDefaults uiDefaults = lnf.getDefaults(); 
        uiDefaults.put("nimbusBase", c); 
        UIManager.getLookAndFeel().uninitialize(); 
        UIManager.setLookAndFeel(lnf); 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 
       UIDefaults defaults = UIManager.getDefaults(); 
       defaults.put("Button.background", c); 
       SwingUtilities.updateComponentTreeUI(button); 
      } 
     }); 
     t.start(); 
    } 

    public static void main(String args[]) { 
     try { 
      for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (Exception e) { 
      return; 
     } 

     java.awt.EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new NimbusTestButtonsBackground().setVisible(true); 
      } 
     }); 
    } 
} 
+0

我會試試看。謝謝。 –