AlexZeCoder
AlexZeCoder

Reputation: 125

Java int - colour only blue?

I wanted to have a background in a java app cycle through all the spectrum colors smoothly. I decided to use integers to define the colors so I could add 1 to it every time it paints a color. The problem is everytime i add 1 it only goes through the shades of blue. Any help?

package Snake;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Alex **** on 02/10/2016.
 */
public class RenderPanel extends JPanel{
    public int curColor = 0;
//    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(new Color(curColor));
        g.fillRect(0, 0, 800, 700);
        curColor++;
    }
}   

Upvotes: 0

Views: 455

Answers (2)

Krzysztof Cichocki
Krzysztof Cichocki

Reputation: 6414

The RGB int Color is constructed as so from bits ( the last three bytes):

RRRRRRRR GGGGGGGG BBBBBBBB

As you can see the:

blue byte is at postion of 0 - 7 bit of the integer.

green byte is at postion of 8 - 15 bit of the integer.

red byte is at postion of 16 - 23 bit of the integer.

if you add 1, you basically just add 1 to blue, to add 1 to green you need to add 256, and to add 1 to red you need to add 65536.

These are just how the binary works - the int number is one, but is used as three bytes, each byte for each part of the RGB color.

Your code will eventually go thru all shades of all colours, but I think you'd like to have effect of the flashing colours. In that case use the HSB space.

So you don't really need all shades of all colours, but only some representative colours for some level of brightness and saturation. In that case generate your color using the method below, the inputs are from range 0.0 to 1.0 float, the part responsible for the color is the hue (h) parameter.

Color.getHSBColor(h, s, b)

So it could be:

package Snake;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Alex **** on 02/10/2016.
 */
public class RenderPanel extends JPanel{
    public int curColor = 0;
//    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.getHSBColor((curColor%256)/256f, 0.5f, 0.5f));
        g.fillRect(0, 0, 800, 700);
        curColor++;
    }
}  

Upvotes: 2

yeoman
yeoman

Reputation: 1681

Your curtain color should move from black to blue, then from black with an invisible bit of green to blue with an invisible bit of green.

After 255 walks from first black to blue it'll then be green to cyan.

The red takes one step up every 65536 blue steps. In total it will take about 16.7 million blue steps i.e., over 65000 green steps, to go from black to white :)

It's not blue only. It's just slow :)

Upvotes: 2

Related Questions