下面列出了怎么用javax.swing.plaf.ColorUIResource的API类实例代码及写法,或者点击链接到github查看源代码。
public static ColorUIResource makeAdjustedForeground(final Color fg, final Color bg, final Bias bias,
final double minimumBrightnessDifference) {
final double[] hslFG = DarkColorModelHSL.RGBtoHSLValues(fg.getRed(), fg.getGreen(), fg.getBlue());
final double[] hslBG = DarkColorModelHSL.RGBtoHSLValues(bg.getRed(), bg.getGreen(), bg.getBlue());
double bgBrightness = hslBG[2];
double fgBrightness = hslFG[2];
Bias b = bias != null ? bias : Bias.getBackground();
if (b == Bias.BACKGROUND) {
double bgBright = ColorUtil.getLuminance(bg);
b = bgBright <= b.threshold ? Bias.WHITE : Bias.BLACK;
}
double bright1 = fgBrightness > bgBrightness && (fgBrightness - bgBrightness) >= minimumBrightnessDifference
? hslFG[2]
: Math.min(bgBrightness + minimumBrightnessDifference, 1);
double bright2 = fgBrightness < bgBrightness && (bgBrightness - fgBrightness) >= minimumBrightnessDifference
? hslFG[2]
: Math.max(bgBrightness - minimumBrightnessDifference, 0);
double brightness = b == Bias.WHITE ? bright1 : bright2;
return new DarkColorUIResource(DarkColorModelHSL.getColorFromHSLValues(hslFG[0], hslFG[1], brightness));
}
private String getComponentName(final String key, final Object value) {
// The key is of the form:
// "componentName.componentProperty", or
// "componentNameUI", or
// "someOtherString"
String componentName;
final int pos = componentNameEndOffset(key);
if (pos != -1) {
componentName = key.substring(0, pos);
} else if (key.endsWith("UI")) {
componentName = key.substring(0, key.length() - 2);
} else if (value instanceof ColorUIResource) {
componentName = "System Colors";
} else {
componentName = "Miscellaneous";
}
// Fix inconsistency
if (componentName.equals("Checkbox")) {
componentName = "CheckBox";
}
return componentName;
}
/**
* Creates and returns a new color derived from the passed in color.
* The transformation is done in the HLS color space using the specified
* arguments to scale.
*
* @param color Color to alter
* @param hFactory Amount to scale the hue
* @param lFactor Amount to scale the lightness
* @param sFactory Amount to sacle saturation
* @return newly created color
*/
static Color adjustColor(Color color, float hFactor, float lFactor,
float sFactor) {
float h;
float l;
float s;
synchronized(HLS_COLOR_LOCK) {
float[] hls = rgbToHLS(color.getRGB(), HLS_COLORS);
h = hls[0];
l = hls[1];
s = hls[2];
}
h = Math.min(360, hFactor * h);
l = Math.min(1, lFactor * l);
s = Math.min(1, sFactor * s);
return new ColorUIResource(hlsToRGB(h, l, s));
}
/**
* http://www.jetbrains.org/intellij/sdk/docs/reference_guide/ui_themes/themes_customize.html#defining-named-colors
*/
private void loadNamedColors( UIDefaults defaults ) {
if( colors == null )
return;
namedColors = new HashMap<>();
for( Map.Entry<String, String> e : colors.entrySet() ) {
String value = e.getValue();
ColorUIResource color = UIDefaultsLoader.parseColor( value );
if( color != null ) {
String key = e.getKey();
namedColors.put( key, color );
defaults.put( "ColorPalette." + key, color );
}
}
}
private void applyColorPalette( UIDefaults defaults ) {
if( icons == null )
return;
Object palette = icons.get( "ColorPalette" );
if( !(palette instanceof Map) )
return;
@SuppressWarnings( "unchecked" )
Map<String, Object> colorPalette = (Map<String, Object>) palette;
for( Map.Entry<String, Object> e : colorPalette.entrySet() ) {
String key = e.getKey();
Object value = e.getValue();
if( key.startsWith( "Checkbox." ) || !(value instanceof String) )
continue;
if( dark )
key = StringUtils.removeTrailing( key, ".Dark" );
ColorUIResource color = toColor( (String) value );
if( color != null )
defaults.put( key, color );
}
}
/**
* parse a comma delimited list of 3 strings into a Color
*/
private ColorUIResource parseColor(String s) {
int red = 0;
int green = 0;
int blue = 0;
try {
StringTokenizer st = new StringTokenizer(s, ",");
red = Integer.parseInt(st.nextToken());
green = Integer.parseInt(st.nextToken());
blue = Integer.parseInt(st.nextToken());
} catch (Exception e) {
System.out.println(e);
System.out.println("Couldn't parse color :" + s);
}
return new ColorUIResource(red, green, blue);
}
/**
* parse a comma delimited list of 3 strings into a Color
*/
private ColorUIResource parseColor(String s) {
int red = 0;
int green = 0;
int blue = 0;
try {
StringTokenizer st = new StringTokenizer(s, ",");
red = Integer.parseInt(st.nextToken());
green = Integer.parseInt(st.nextToken());
blue = Integer.parseInt(st.nextToken());
} catch (Exception e) {
System.out.println(e);
System.out.println("Couldn't parse color :" + s);
}
return new ColorUIResource(red, green, blue);
}
void testNames() {
Color defaultColor = label.getBackground();
UIManager.put("\"BlueLabel\"[Enabled].background",
new ColorUIResource(Color.BLUE));
UIManager.put("\"RedLabel\"[Enabled].background",
new ColorUIResource(Color.RED));
nimbus.register(Region.LABEL, "\"BlueLabel\"");
nimbus.register(Region.LABEL, "\"RedLabel\"");
label.setName("BlueLabel");
check(Color.BLUE);
label.setName("RedLabel");
check(Color.RED);
// remove name, color goes back to default
label.setName(null);
check(defaultColor);
}
private static Color parseColorString(String str) {
if (str.charAt(0) == '#') {
str = str.substring(1);
int i = str.length();
if (i < 3 || i > 12 || (i % 3) != 0) {
return null;
}
i /= 3;
int r;
int g;
int b;
try {
r = Integer.parseInt(str.substring(0, i), 16);
g = Integer.parseInt(str.substring(i, i * 2), 16);
b = Integer.parseInt(str.substring(i * 2, i * 3), 16);
} catch (NumberFormatException nfe) {
return null;
}
if (i == 4) {
return new ColorUIResource(r / 65535.0f, g / 65535.0f, b / 65535.0f);
} else if (i == 1) {
return new ColorUIResource(r / 15.0f, g / 15.0f, b / 15.0f);
} else if (i == 2) {
return new ColorUIResource(r, g, b);
} else {
return new ColorUIResource(r / 4095.0f, g / 4095.0f, b / 4095.0f);
}
} else {
return XColors.lookupColor(str);
}
}
private void explicitColorsChanged() {
EventQueue.invokeLater( () -> {
boolean explicit = explicitColorsCheckBox.isSelected();
ColorUIResource restoreColor = new ColorUIResource( Color.white );
boolean dark = FlatLaf.isLafDark();
Color magenta = dark ? Color.magenta.darker() : Color.magenta;
Color orange = dark ? Color.orange.darker() : Color.orange;
Color blue = dark ? Color.blue.darker() : Color.blue;
Color green = dark ? Color.green.darker() : Color.green;
updateComponentsRecur( content, (c, type) -> {
if( type == "view" || type == "tab" ) {
c.setForeground( explicit ? magenta : restoreColor );
c.setBackground( explicit ? orange : restoreColor );
} else {
c.setForeground( explicit ? blue : restoreColor );
c.setBackground( explicit ? green : restoreColor );
}
} );
// because colors may depend on state (e.g. disabled JTextField)
// it is best to update all UI delegates to get correct result
if( !explicit )
SwingUtilities.updateComponentTreeUI( content );
} );
}
private ColorUIResource toColor( String value ) {
// map named colors
ColorUIResource color = namedColors.get( value );
// parse color
return (color != null) ? color : UIDefaultsLoader.parseColor( value );
}
/**
* Syntax: hsl(hue,saturation,lightness) or hsla(hue,saturation,lightness,alpha)
* - hue: an integer 0-360 representing degrees
* - saturation: a percentage 0-100%
* - lightness: a percentage 0-100%
* - alpha: a percentage 0-100%
*/
private static ColorUIResource parseColorHslOrHsla( boolean hasAlpha, List<String> params ) {
int hue = parseInteger( params.get( 0 ), 0, 360, false );
int saturation = parsePercentage( params.get( 1 ) );
int lightness = parsePercentage( params.get( 2 ) );
int alpha = hasAlpha ? parsePercentage( params.get( 3 ) ) : 100;
float[] hsl = new float[] { hue, saturation, lightness };
return new ColorUIResource( HSLColor.toRGB( hsl, alpha / 100f ) );
}
private static Color parseColorString(String str) {
if (str.charAt(0) == '#') {
str = str.substring(1);
int i = str.length();
if (i < 3 || i > 12 || (i % 3) != 0) {
return null;
}
i /= 3;
int r;
int g;
int b;
try {
r = Integer.parseInt(str.substring(0, i), 16);
g = Integer.parseInt(str.substring(i, i * 2), 16);
b = Integer.parseInt(str.substring(i * 2, i * 3), 16);
} catch (NumberFormatException nfe) {
return null;
}
if (i == 4) {
return new ColorUIResource(r / 65535.0f, g / 65535.0f, b / 65535.0f);
} else if (i == 1) {
return new ColorUIResource(r / 15.0f, g / 15.0f, b / 15.0f);
} else if (i == 2) {
return new ColorUIResource(r, g, b);
} else {
return new ColorUIResource(r / 4095.0f, g / 4095.0f, b / 4095.0f);
}
} else {
return XColors.lookupColor(str);
}
}
void testInheritance() {
Color defaultColor = label.getBackground();
// more specific setting is in global defaults
UIManager.put("Label[Enabled].background", new ColorUIResource(Color.RED));
// less specific one is in overrides
UIDefaults defs = new UIDefaults();
defs.put("Label.background", new ColorUIResource(Color.GREEN));
// global wins
label.putClientProperty("Nimbus.Overrides", defs);
check(Color.RED);
// now override wins
label.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
check(Color.GREEN);
// global is back
label.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
check(Color.RED);
// back to default color
UIManager.put("Label[Enabled].background", null);
label.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
label.putClientProperty("Nimbus.Overrides", null);
check(defaultColor);
}
public static ColorUIResource makeForeground(final Color bg) {
return makeForeground(bg, MIN_FOREGROUND_DIFFERENCE);
}
public static ColorUIResource makeForeground(final Color bg, final double minimumBrightnessDifference) {
double[] hsbBG = DarkColorModelHSB.RGBtoHSBValues(bg.getRed(), bg.getGreen(), bg.getBlue());
Color fg = DarkColorModelHSB.getColorFromHSBValues(hsbBG[0], 0, 1 - hsbBG[2]);
return makeAdjustedForeground(fg, bg, Bias.getBackground(), minimumBrightnessDifference);
}
@Override
protected ColorUIResource getPrimary2() {
return primary2;
}
protected Expression instantiate(Object oldInstance, Encoder out) {
Color color = (Color) oldInstance;
Object[] args = new Object[] {color.getRGB()};
return new Expression(color, ColorUIResource.class, "new", args);
}
@Override
protected ColorUIResource getPrimary3() {
return primary3;
}
private void popupMenubackgroundChanged() {
UIManager.put( "PopupMenu.background", popupMenubackgroundCheckBox.isSelected()
? new ColorUIResource( Color.yellow )
: null );
FlatLaf.updateUI();
}
@Override
protected ColorUIResource getPrimary1() {
return primary1;
}
static ColorUIResource parseColor( String value ) {
return parseColor( value, false );
}
@Override
protected ColorUIResource getSecondary3() {
return secondary3;
}
/**
* Syntax: lighten(color,amount[,options]) or darken(color,amount[,options]) or
* saturate(color,amount[,options]) or desaturate(color,amount[,options])
* - color: a color (e.g. #f00) or a color function
* - amount: percentage 0-100%
* - options: [relative] [autoInverse] [noAutoInverse] [lazy] [derived]
*/
private static Object parseColorHSLIncreaseDecrease( int hslIndex, boolean increase,
List<String> params, Function<String, String> resolver, boolean reportError )
{
String colorStr = params.get( 0 );
int amount = parsePercentage( params.get( 1 ) );
boolean relative = false;
boolean autoInverse = false;
boolean lazy = false;
boolean derived = false;
if( params.size() > 2 ) {
String options = params.get( 2 );
relative = options.contains( "relative" );
autoInverse = options.contains( "autoInverse" );
lazy = options.contains( "lazy" );
derived = options.contains( "derived" );
// use autoInverse by default for derived colors, except if noAutoInverse is set
if( derived && !options.contains( "noAutoInverse" ) )
autoInverse = true;
}
// create function
ColorFunction function = new ColorFunctions.HSLIncreaseDecrease(
hslIndex, increase, amount, relative, autoInverse );
if( lazy ) {
return (LazyValue) t -> {
Object color = lazyUIManagerGet( colorStr );
return (color instanceof Color)
? new ColorUIResource( ColorFunctions.applyFunctions( (Color) color, function ) )
: null;
};
}
// parse base color
String resolvedColorStr = resolver.apply( colorStr );
ColorUIResource baseColor = (ColorUIResource) parseColorOrFunction( resolvedColorStr, resolver, reportError );
// apply this function to base color
Color newColor = ColorFunctions.applyFunctions( baseColor, function );
if( derived ) {
ColorFunction[] functions;
if( baseColor instanceof DerivedColor && resolvedColorStr == colorStr ) {
// if the base color is also derived, join the color functions
// but only if base color function is specified directly in this function
ColorFunction[] baseFunctions = ((DerivedColor)baseColor).getFunctions();
functions = new ColorFunction[baseFunctions.length + 1];
System.arraycopy( baseFunctions, 0, functions, 0, baseFunctions.length );
functions[baseFunctions.length] = function;
} else
functions = new ColorFunction[] { function };
return new DerivedColor( newColor, functions );
}
return new ColorUIResource( newColor );
}
@Override
protected ColorUIResource getPrimary1() {
return primary1;
}
@Override
protected ColorUIResource getPrimary2() {
return primary2;
}
protected Expression instantiate(Object oldInstance, Encoder out) {
Color color = (Color) oldInstance;
Object[] args = new Object[] {color.getRGB()};
return new Expression(color, ColorUIResource.class, "new", args);
}
@Override
public ColorUIResource getPrimaryControlHighlight() {
return primaryHighlight;
}
@Override
protected ColorUIResource getSecondary2() {
return secondary2;
}
@Override
protected ColorUIResource getSecondary3() {
return secondary3;
}