package rolldice;
import java.awt.*;
import javax.swing.*;
public class Die extends JComponent {
private static final int SPOT_DIAM = 9;
private int _faceValue;
public Die() {
setPreferredSize(new Dimension(60,60));
roll();
}
public int roll() {
int val = (int)(6*Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return _faceValue;
}
public void setValue(int spots) {
_faceValue = spots;
repaint();
}
@Override public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
g2.fillRect(0, 0, w, h);
g2.setColor(Color.GREEN);
g2.drawRect(0, 0, w-1, h-1);
switch (_faceValue) {
case 1:
drawSpot(g2, w/2, h/2);
break;
case 3:
drawSpot(g2, w/2, h/2);
case 2:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
break;
case 5:
drawSpot(g2, w/2, h/2);
case 4:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
break;
case 6:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
drawSpot(g2, w/4, h/2);
drawSpot(g2, 3*w/4, h/2);
break;
}
}
private void drawSpot(Graphics2D g2, int x, int y) {
g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
}
}
ria_ria
0
Newbie Poster
Recommended Answers
Jump to PostI think you dint posted the entire code..
Also attach your output screenshot if possible..
Jump to PostDo you want it to keep on showing a new random face at regular intervals?
If so, use a javax.swing.Timer to call your roll() method with a suitable interval:
http://download.oracle.com/javase/tutorial/uiswing/misc/timer.html
Jump to Postplease modify it. thank you for your help.
No, that's not how it works here. Nobody is going to do your homework for you.
I gave you some pointers in my last post. Now its up to you to do some work. Check out the timer class I told you …
All 9 Replies
harinath_2007
56
Posting Whiz
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
ria_ria
0
Newbie Poster
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
Taywin
312
Posting Virtuoso
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
Taywin
312
Posting Virtuoso
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
Taywin
312
Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.