Java Nimbus Look and Feel组件自定义问题:配置影响其他实例
Hey there, I’ve run into this exact gotcha with Nimbus before—total head-scratcher at first! The issue here isn’t actually a bug, but a tricky behavior in how Nimbus handles the Nimbus.Overrides client property.
Why This Happens
When you pass a UIDefaults instance to putClientProperty("Nimbus.Overrides", overrides), Nimbus stores a direct reference to that object instead of creating a deep copy. If you reuse the same UIDefaults instance across multiple components, all of them will share those overrides. Even small changes to that shared instance later on will affect every component using it, making it look like your customizations are leaking.
How to Fix It
Here are two reliable ways to isolate your component-specific overrides:
Create a fresh
UIDefaultsinstance for each component
This ensures each component has its own independent set of overrides, so there’s no shared reference to cause cross-contamination. Example code:// Customize first button UIDefaults redButtonOverrides = new UIDefaults(); redButtonOverrides.put("Button.background", Color.RED); redButton.putClientProperty("Nimbus.Overrides", redButtonOverrides); // Customize second button with a new instance UIDefaults blueButtonOverrides = new UIDefaults(); blueButtonOverrides.put("Button.background", Color.BLUE); blueButton.putClientProperty("Nimbus.Overrides", blueButtonOverrides);Add the
Nimbus.Overrides.InheritDefaultsproperty
Setting this totruetells Nimbus that the component should only use its own overrides and not inherit unintended defaults from shared objects. Pair this with a uniqueUIDefaultsinstance for extra safety:UIDefaults customOverrides = new UIDefaults(); customOverrides.put("Label.foreground", Color.DARK_GRAY); myLabel.putClientProperty("Nimbus.Overrides", customOverrides); // Isolate this component's overrides myLabel.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
Pro Tip
Avoid modifying a UIDefaults instance after attaching it to a component. If you need to update a component’s styling later, create a new UIDefaults instance with the changes and reapply it—this prevents unexpected updates to other components.
内容的提问来源于stack exchange,提问作者Tom

