Add Dots on Die and Mouse Click Listener
Learn to add dots on the die for 1,2,3,4,5,6, and change the state of the die on clicking.
Placing dots on the die
Add dots on a die.
Adding a center dot
Circles are normally drawn inside a rectangular area whose upper left corner is at x
and y
. Placement for the dots on the die would be easier to calculate if circle placement was instead based on the center of the circle.
The dots for all the dice will need to be 10 pixels in diameter, centered at x
and y
.
- Add a private method called
drawDot()
. It should take three parameters: one Graphics object calledg
, and two integers calledx
andy
, and return nothing. drawDot()
will need to fill a circle on g that is 10 pixels wide and10
pixels tall, starting at5
pixels to the left ofx
and5
pixels abovey
. Use Graphics’fillOval()
method.
...
private void drawDot(Graphics g, int x, int y) {
g.fillOval(x-5, y-5, 10, 10);
}
...
In the draw the dots section of paintComponent()
, draw a dot in the center of the die. Use drawDot()
. Use WIDTH
and HEIGHT
to calculate the center of the die.
...
public void paintComponent(Graphics g) {
...
// draw the dots
drawDot(g, WIDTH/2, HEIGHT/2);
}
...
Add the above code. Then, click the “run” button, a black dot will be centered in the die.
Adding dots for die values 1
, 3
, and 5
The same dots appear on several dice. For example, the dice with values of 1, 3, and 5, all have a center dot. Dice with values of 3 and 5 both have dots in the upper left corner and lower right corner. Dice with a value of 5 also have dots in the upper-right and lower-left corners. These three arrangements of dots could be implemented using a switch statement without a break between the cases.
- Remove the code in
paintComponent()
that draws the dot in the center. - Replace the removed code with a switch block that tests
value
, and then draws a center dot if the value is1
, draws that center dot, plus upper right and lower left dots, if the value is3
, and draws those same dots, plus the upper left and lower right dots if the value is5
. Draw dots for5
first, then for3
, then for1
, without break statements. Then, place the dots 1/4 of the die size away from the edge.
...
public void paintComponent(Graphics g) {
...
// draw the dots
switch(__________) {
case 5:
drawDot(________________);
drawDot(________________);
case 3:
drawDot(________________);
drawDot(________________);
case 1:
drawDot(________________);
}
...
Get hands-on with 1200+ tech skills courses.