Java Reference
In-Depth Information
returns a random double value between 0 and 1 . Note that the third constructor of the
Color class (see Table 12-5) takes three float values, each between 0 and 1 ,as
parameters. Therefore, we use the explicit cast operator ( float ) to convert the double
value returned by the random method. Thus, we use the following statements to
randomly generate a value for the colors red, green, and blue:
red = ( float ) Math.random();
green = ( float ) Math.random();
blue = ( float ) Math.random();
These statements assign random float values between 0 and 1 to the float variables
red , green , and blue . Suppose that bottomrightJL is a JLabel . The statement:
bottomrightJL.setForeground( new Color(red, green, blue));
creates a color and assigns it as the foreground color of the label bottomrightJL .
EXAMPLE 12-2
This example gives the complete program listing and a sample run that shows how to set
the colors of a text and GUI components.
//ColorsDisplayed Applet
import java.awt.*;
import javax.swing.*;
public class ColorsDisplayed extends JApplet
{
JLabel topleftJL, toprightJL, bottomleftJL, bottomrightJL;
int i;
float red, green, blue;
public void init()
{
Container c = getContentPane();
1
2
c.setLayout( new GridLayout(2, 2));
c.setBackground(Color.white);
topleftJL = new JLabel("Red", SwingConstants.CENTER);
toprightJL = new JLabel("Green", SwingConstants.CENTER);
bottomleftJL = new JLabel("Blue",
SwingConstants.CENTER);
bottomrightJL = new JLabel("Random",
SwingConstants.CENTER);
topleftJL.setForeground(Color.red);
toprightJL.setForeground(Color.green);
bottomleftJL.setForeground(Color.blue);
Search WWH ::




Custom Search