So in our Java class assignment, we are supposed to display a three color gradient on a JPanel Canvas. To get the colors, we are supposed to calculate R,G,B variables by ourselves, and as a result, have three colors to pass to the gradient bar.
Example
Color 1 = 0,0,0
Color 2 = 255,0,0
Color 3 = 255,255,255
So the gradient should go from solid black, to red, then to white. The colors are calculated based on Intensity. (Intensity 0 = black color. Intensity 128 = 255 red, 50 green, 0 blue. Intensity 255 = white color)
public class ColorGradient {
public void gradient() {
float intensity = 255;
float r1 = 0;
float g1 = 0;
float b1 = 0;
if (intensity <= 128) {
r1 = ((float)255/(float)128)*intensity;
g1 = ((float)50/(float)128)*intensity;
b1 = ((float)0/(float)128)*intensity;
System.out.println(r1);
System.out.println(g1);
System.out.println(b1);
} else {
r1 = 255;
g1 = 50 + (((float)205/(float)128)*(intensity-128));
b1 = (((float)255/(float)128)*(intensity-128));
System.out.println((int)r1);
System.out.println((int)g1);
System.out.println((int)b1);
}
}
}
We made a class to calculate the numbers (but not as exact as possible), but we are not sure how to pass each Color to the Panel as one Gradient. GradientPaint only takes two colors, so we have no three color bar.
I assume we create three "new" Colors from our output above? Its just, we are currently stuck at how to put the Bar on the Jpanel Canvas.
//possible example
Color c1 = new Color(0,0,0) //black part of the Gradient
Color c2 = new Color(255,50,0) // red part of the Gradient
Color c3 = new Color(255,255,255) // white part of the Gradient
Gradient example from our class
We have a function to put the Gradient on the Canvas, and if we use GradientPaint from awt we are able to make a 2 color Gradient (but I assume this is not the right way)
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
GradientPaint blackToRed = new GradientPaint(0,0, Color.black, 100,20,Color.red);
g2.setPaint(blackToRed);
g2.fill(new Rectangle2D.Double(0,0,200,20));
}