Java colors and their rgb values code example
The problem with this technique is that two colors with similar hues, but different saturation or brightness levels may map further away from each other in 3D RGB space than two colors with different hues, but very similar saturation and brightness levels. In the code snippet below, this is done in the ´createColorsArrayArgb` method, which creates an array of ARGB colors from an arbitrary sequence of colors (I needed this recently).
How do I find the RGB representation of a Color object? [duplicate]
You can use getBlue() , getGreen() , and getRed() .
Color yellow = Color.YELLOW; System.out.printf("red: %d, green: %d, blue: %d", yellow.getRed(), yellow.getGreen(), yellow.getBlue());
And if you wish to extract the alpha channel as well, you can use getAlpha() .
It really depends on the exact color that you want. I would play around with different numbers and gain an understanding for how the colors work. They go from dark to light, where dark is 0 and light is 255, so (255,255,255) is white and (0,0,0) is black. To get a yellowish color, play around with a medium red value and equal green and blue values that are fairly high.
I am assuming you want the hex string that you can use in HTML. I would do it like this.
public String toRgb(Color arg)
RGB Color – HTML and CSS Guide, The color red is not showing whereas green and blue are at their brightest and at their max. White is rgb(255,255,255) Black is rgb(0,0,0) Red is rgb(255,0,0) Green is rgb(0,255,0) Blue is rgb(0,0,255) Lots of Options with RGB. With RGB, each value is mixed in with the rest and together they create a wide …
How to know what r,g,b values to use for get other colours to paint a JFrame dynamically?
Your current approach is indeed not easily generalizable. The hard-coded parts of the buttons for «blue» and «green», and especially the special methods like blueToGreen make it impossible to extend the number of colors with reasonable effort. (You don’t want to create methods blueToYellow , blueToRed , blueToTheThirdColorFromThisListForWhichIDontKnowAName . ).
There are many possible ways of generalizing this. You did not say much about the intended structure and responsibilities. But you should at least create a method that can interpolate between two arbitrary colors with a given number of steps. In the code snippet below, this is done in the ´createColorsArrayArgb` method, which creates an array of ARGB colors from an arbitrary sequence of colors (I needed this recently). But you can probably boil it down to 2 colors, if you want to.
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; public class ChangeColor < public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < @Override public void run() < new ChangeColor(); >>); > public ChangeColor() < JFrame frame = new JFrame(); ColorPanel colorPanel = new ColorPanel(Color.BLUE); ColorInterpolator ci = new ColorInterpolator(colorPanel, Color.BLUE); colorPanel.addColorButton(createButton("Blue", Color.BLUE, ci)); colorPanel.addColorButton(createButton("Green", Color.GREEN, ci)); colorPanel.addColorButton(createButton("Red", Color.RED, ci)); colorPanel.addColorButton(createButton("Cyan", Color.CYAN, ci)); colorPanel.addColorButton(createButton("Yellow", Color.YELLOW, ci)); colorPanel.addColorButton(createButton("Magenta", Color.MAGENTA, ci)); frame.add(colorPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); >private static JButton createButton(String name, final Color color, final ColorInterpolator colorInterpolator) < JButton button = new JButton(name); button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent e) < colorInterpolator.interpolateTo(color); >>); return button; > /** * Creates an array with the given number of elements, that contains the * ARGB representations of colors that are linearly interpolated between the * given colors * * @param steps The number of steps (the size of the resulting array) * @param colors The colors to interpolate between * @return The array with ARGB colors */ static int[] createColorsArrayArgb(int steps, Color. colors) < int result[] = new int[steps]; double normalizing = 1.0 / (steps - 1); int numSegments = colors.length - 1; double segmentSize = 1.0 / (colors.length - 1); for (int i = 0; i < steps; i++) < double relative = i * normalizing; int i0 = Math.min(numSegments, (int) (relative * numSegments)); int i1 = Math.min(numSegments, i0 + 1); double local = (relative - i0 * segmentSize) * numSegments; Color c0 = colors[i0]; int r0 = c0.getRed(); int g0 = c0.getGreen(); int b0 = c0.getBlue(); Color c1 = colors[i1]; int r1 = c1.getRed(); int g1 = c1.getGreen(); int b1 = c1.getBlue(); int dr = r1 - r0; int dg = g1 - g0; int db = b1 - b0; int r = (int) (r0 + local * dr); int g = (int) (g0 + local * dg); int b = (int) (b0 + local * db); int argb = (0xFF return result; > > class ColorInterpolator < private static final int DELAY = 20; private Color currentColor; private int currentIndex = 0; private int currentColorsArgb[]; private final Timer timer; private final ColorPanel colorPanel; ColorInterpolator(final ColorPanel colorPanel, Color initialColor) < this.colorPanel = colorPanel; currentColor = initialColor; currentColorsArgb = new int[]< initialColor.getRGB() >; timer = new Timer(DELAY, new ActionListener() < @Override public void actionPerformed(ActionEvent e) < currentIndex++; if (currentIndex >= currentColorsArgb.length-1) < timer.stop(); colorPanel.enableButtons(); >else < int argb = currentColorsArgb[currentIndex]; currentColor = new Color(argb); colorPanel.setColor(currentColor); >> >); > void interpolateTo(Color targetColor) < colorPanel.diableButtons(); currentColorsArgb = ChangeColor.createColorsArrayArgb( 40, currentColor, targetColor); currentIndex = 0; timer.start(); >> class ColorPanel extends JPanel < private Color currentColor; private Listbuttons; public ColorPanel(Color initialColor) < currentColor = initialColor; buttons = new ArrayList(); > void addColorButton(JButton button) < buttons.add(button); add(button); >public void diableButtons() < for (JButton button : buttons) < button.setEnabled(false); >> public void enableButtons() < for (JButton button : buttons) < button.setEnabled(true); >> public void setColor(Color color) < currentColor = color; repaint(); >@Override protected void paintComponent(Graphics g) < super.paintComponent(g); g.setColor(currentColor); g.fillRect(0, 0, getWidth(), getHeight()); >@Override public Dimension getPreferredSize() < return new Dimension(600, 300); >>
For simplicity, you might look at doing the fade calculation in HSB color coordinates. The example below interpolates between the two hues, green and blue, but you can pass saturation and brightness, too. The color lookup table, clut , is precomputed and used in the timer’s listener. Some related examples are seen here.
import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.Queue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; /** * @see https://stackoverflow.com/a/24718561/230513 */ public class HSBTest < private static final float greenHue = 2 / 6f; private static final float blueHue = 4 / 6f; private void display() < JFrame f = new JFrame("HSBTest"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Fader fader = new Fader(greenHue, blueHue); f.add(fader); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); fader.start(); >private static class Fader extends JPanel implements ActionListener < private final float N = 32; private final Queueclut = new LinkedList(); Timer t = new Timer(50, this); public Fader(float h1, float h2) < float d = (h2 - h1) / N; for (int i = 0; i < N; i++) < clut.add(Color.getHSBColor(h1 + d * i, 1, 1)); >for (int i = 0; i < N; i++) < clut.add(Color.getHSBColor(h2 - d * i, 1, 1)); >> private void start() < t.start(); >@Override public void actionPerformed(ActionEvent e) < this.setBackground(clut.peek()); clut.add(clut.remove()); >@Override public Dimension getPreferredSize() < return new Dimension(256, 128); >> public static void main(String[] args) < EventQueue.invokeLater(new Runnable() < @Override public void run() < new HSBTest().display(); >>); > >
public void actionPerformed(ActionEvent e) < Listcolors = new ArrayList(); colors.add(new Color(0,0,255); colors.add(new Color(255,0,0); colors.add(new Color(0,255,0); // add your other colors for(Color c : colors) < setColor(c) Thread.sleep(1000); //wait 1 second to change the color repaint(); >>
Java — How to automatically generate N «distinct» colors, I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that’s what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB …
Color Logic Algorithm
Here is a theoretical explanation
typedef struct < unsigned char r, g, b; >RGB; double ColourDistance(RGB e1, RGB e2) < long rmean = ( (long)e1.r + (long)e2.r ) / 2; long r = (long)e1.r - (long)e2.r; long g = (long)e1.g - (long)e2.g; long b = (long)e1.b - (long)e2.b; return sqrt((((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8)); >
Here is pgras’ algorithm in Java:
public double ColourDistance(Color c1, Color c2) < double rmean = ( c1.getRed() + c2.getRed() )/2; int r = c1.getRed() - c2.getRed(); int g = c1.getGreen() - c2.getGreen(); int b = c1.getBlue() - c2.getBlue(); double weightR = 2 + rmean/256; double weightG = 4.0; double weightB = 2 + (255-rmean)/256; return Math.sqrt(weightR*r*r + weightG*g*g + weightB*b*b); >
Most answers for this question will suggest calculating the distance between two colors when mapping the RGB values into a 3D space. The problem with this technique is that two colors with similar hues, but different saturation or brightness levels may map further away from each other in 3D RGB space than two colors with different hues, but very similar saturation and brightness levels. In other words, a blue and a green may be closer in 3D RGB space than two shades of a Red. In this application, ensuring team colors differ, hue differences should weigh much more heavily than brightness and saturation.
So I would convert the color mapping from RGB to hue, saturation, and brightness levels, and then check just the hue values for sufficient distance.
Wikipedia has an explanation for converting RGB to HSV. LiteratePrograms has some sample code.