Colors are easy: just ask the Graphics object to set the color, and then that color is used for that Graphics object until you tell it otherwise. For example:
graphics2.setColor(Color.red);
graphics2.draw(new Rectangle(10, 430, 20, 40));
graphics2.draw(new Ellipse2D.Double(5, 440, 40, 20));
graphics2.setColor(new Color(0, 128, 255));
graphics2.fill(new Ellipse2D.Double(30, 470, 20, 40));
graphics2.setColor(new Color(255, 0, 0, 50));
graphics2.fill(new Ellipse2D.Double(80, 480, 40, 30));
Note how I used:
- The pre-defined color Color.red for drawing the first two objects above
- A color constructor for drawing the third object: the constructor specifies the amount of red, green and blue, respectively,
in the Color, where each parameter ranges between 0 (none of that color) to 255 (all of that color).
- For drawing the fourth object, a color constructor that takes four parameters — the fourth parameter
is the degree of transparancy; try it to see what it does!
- The fill method — try it to see what it does!
- Draw a few more objects, of any sort you wish, using colors.
- Use at least one pre-defined Color and at least one constructed Color.
- Make at least some of your new objects be filled instead of drawn.
- The picture to the right shows some examples — but yours can be with whatever shapes and colors you want,
subject to the above restrictions.
- Draw a filled rounded rectangle, like the blue one shown in the picture to the right.
- It can appear anywhere you want, of any size you want, as long as it is readily visible and clearly “rounded”.
- I'm purposely not telling you how to draw a rounded rectangle — do some detective work! (But not more than a few minutes worth; ask questions as needed.)
- Draw a filled red rectangle that is at the very bottom of the window.
It can have whatever (reasonably visible) height you want,
but its width should be the width of the JComponent that you are drawing on.
- So if the user resizes the window, the red rectangle should grow or shrink per the resize, and it should “stick” to the bottom of the window.
Test your understanding: Answer these questions on the
self test that accompanies this exercise.
- Write a statement that sets the color of the Graphics object named g to the predefined color cyan.
- Write a statement that sets the color of the Graphics object named g to half red and half green and no blue.
- True or false: once you use setColor to set the color for a Graphics object,
all subsequent drawing and filling on that Graphics object will be in that color,
unless you do another setColor on that Graphics object.
- What is the name of the class you use to draw rounded rectangles?
|
|
|