import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class ColoredButton extends Applet {

    // The button and the three text fields.
    // Not quite Goldilocks and the three bears.
    private Button button;
    private TextField redField;
    private TextField greenField;
    private TextField blueField;
    
    public void init()
    {
	// Create the GUI components.
	button = new Button("Set Color");
	redField = new TextField();
	greenField = new TextField();
	blueField = new TextField();
	Panel p = new Panel();
	p.setLayout(new GridLayout(3, 2));
	p.add(new Label("Red:", Label.RIGHT));
	p.add(redField);
	p.add(new Label("Green:", Label.RIGHT));
	p.add(greenField);
	p.add(new Label("Blue:", Label.RIGHT));
	p.add(blueField);
	setLayout(new GridBagLayout());
	GridBagConstraints gbc = new GridBagConstraints();
	gbc.gridwidth = GridBagConstraints.REMAINDER;
	gbc.weightx = 1;
	gbc.fill = GridBagConstraints.HORIZONTAL;
	gbc.ipadx = 10;
	gbc.ipady = 10;
	add(p, gbc);
	add(button, gbc);
	// Set action for button.
	button.addActionListener(new ActionListener()
	{
	    public void actionPerformed(ActionEvent ae)
	    {
		setButtonColor();
	    }
	});
	// Set action for red text field
	redField.addActionListener(new ActionListener()
	{
	    public void actionPerformed(ActionEvent ae)
	    {
		setButtonColor();
	    }
	});
	// Set action for green text field.
	greenField.addActionListener(new ActionListener()
	{
	    public void actionPerformed(ActionEvent ae)
	    {
		setButtonColor();
	    }
	});
	// Set action for blue text field.
	blueField.addActionListener(new ActionListener()
	{
	    public void actionPerformed(ActionEvent ae)
	    {
		setButtonColor();
	    }
	});
    }

    private void setButtonColor()
    {
	// Get the colors from the three TextFields
	int red = parseField(redField);
	int green = parseField(greenField);
	int blue = parseField(blueField);
	// Now set the button's background color
	button.setBackground(new Color(red, green, blue));
	// Let's set the Foreground color to be white if the background
	// is too dark.  Otherwise, keep if black.
	if (red < 20 && green < 20 && blue < 20)
	    button.setForeground(Color.white);
	else
	    button.setForeground(Color.black);
    }
    
    private int parseField(TextField tf)
    {
	int value;
	// Only parse valid Strings.
	if (tf == null)
	    return 0;
	String s = tf.getText();
	if (s == null || s.length() == 0)
	    value = 0;
	else
	    value =  Integer.parseInt(s);
	// Keep value within legal color range.
	if (value < 0)
	    value = 0;
	if (value > 255)
	    value = 255;
	// Set TextField value to legal value in case we changed it.
	// First convert to an Integer, and then to a String.
	tf.setText((new Integer(value)).toString());
	return value;
    }
}
