Technical Support
Discussion Forum
Online Training
Read About Java
Java In-Depth
Product Discounts
Membership Information

Java Cup Logo

JDC Home Page


Working Applet
Help and Hints
Source Code
Table of Contents
Online Training
shadowSearchFAQFeedback

Color Help

Help is available for each task, or you can go straight to the Choice source code to see a solution.

Task 1

Create an applet called ColorTest that sets the layout manager to GridLayout(2,2).

import java.awt.*;
public class ColorTest extends java.applet.Applet {

    public void init() {
        setLayout(new GridLayout(2,2));
    }
}

Task 2

Define a class called ColorCanvas that is an extension of Canvas. Set the constructor to accept a Color object, that is stored in an instance variable. Define a lifecyle public void paint(Graphics g) method that sets g's color and fills a rectangle to the full extent of the Canvas. Hint: you can get the size of a Component with method size.

The paint method in a Canvas object is used just like you'd use for an applet--it is called when it is time to refresh the Component. In this case, set the color of the graphics context and then ask the context to draw a filled rectangle using the current color. size returns a Dimension with members width and height that you can access.

class ColorCanvas extends Canvas {
    Color color;
    public ColorCanvas(Color c) {
        color = c;
    }
    public void paint(Graphics g) {
        g.setColor(color);
        g.fillRect(0, 0, size().width, size().height);
    }
}

Task 3

In your applet, create and add four ColorCanvas objects with colors Color.black, Color.red, Color.orange, and Color.yellow.

public void init() {
    setLayout(new GridLayout(2,2));
    add(new ColorCanvas(Color.black));
    add(new ColorCanvas(Color.red));
    add(new ColorCanvas(Color.orange));
    add(new ColorCanvas(Color.yellow));
}