views:

339

answers:

2

I'm working with java.awt.Color instances. Is there any way to do arithmetic operations on colors? Something like rgb(20, 20, 20) + rgb(10, 200, 170) = rgb(30, 220, 190)?

What I'm trying to do: I have a gui that features a table, where if the user clicks on a cell, the other cells change color based on their relationship to the selected one. I'm looking for a way to avoid hard coding what the base colors are, and on which color values they change.

So the selected cell might be rgb(255, 0, 0), and everything else might be between rgb(0, 0, 0) and rgb(0, 255, 0) based on their values. I'm thinking... enums?

import java.awt.Color;

public enum ColorConstant {
    SELECTED (new rgb(255, 0, 0), "Red"),
    MAX_DISTANCE (new rgb(0, 255, 0), "Green")

    private Color shade;
    private ??? whichColorToModify;

}
+5  A: 

There are the methods Color.brighter and Color.darker.

Other than that, I usually write a small utility methods for such purposes, like:

private static Color brightness(Color c, double scale) {
 int r = Math.min(255, (int) (c.getRed() * scale));
 int g = Math.min(255, (int) (c.getGreen() * scale));
 int b = Math.min(255, (int) (c.getBlue() * scale));
 return new Color(r,g,b);
}
meriton
Dude! Never thought about using Math.min but it sure makes sense! D:
Spoike
+1 for using Math.min
William
+2  A: 

HSLColor might be what you are looking for. It allow you to adjust the tone/shade of a color easily.

camickr