While using the Nimbus L&F feel in Java, I am having problems with changing the background color for a JButton more than once. In the code below, I have a simple Swing application that displays a JButton and attempts to change the color once per second. However, only the first color is being applied. Can anyone provide any suggestions on how to make this change more than once? I'm running java 6.29.
public class NimbusTest3 extends JFrame {
private javax.swing.JButton button;
public NimbusTest3(){
button = new javax.swing.JButton();
button.setText("Text");
this.add(button, BorderLayout.CENTER);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.pack();
Timer t = new Timer(1000, new ActionListener() {
Random r = new Random();
@Override
public void actionPerformed(ActionEvent e) {
UIDefaults buttonDefaults = UIManager.getLookAndFeelDefaults();
Color c = new Color(r.nextInt(
256), r.nextInt(256), r.nextInt(256));
System.out.println(c);
buttonDefaults.put("Button.background", c);
button.putClientProperty("Nimbus.Overrides", buttonDefaults);
button.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
SwingUtilities.updateComponentTreeUI(button);
button.repaint();
}
});
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 NimbusTest3().setVisible(true);
}
});
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…