flybonzai flybonzai - 1 year ago 90
Java Question

Graphics.paintComponents .drawString method not placing numbers on my dice roller

I'm working on a basic dice roller GUI, and I'm down to trying to get the numbers to display on the dice when I roll. Currently everything looks right except for my dice are blank. Here is my code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class DiceRoller extends JPanel {

public DiceRoller() {

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Dice Roller");
frame.setContentPane(new ViewPanel());
frame.pack(); //To set frame so contents are at or above preferred size.

class ViewPanel extends JPanel {
// Initialize the two dice
private Dice dice1;
private Dice dice2;

ViewPanel() {
dice1 = new Dice();
dice2 = new Dice();

JButton rollButton = new JButton("Roll");
rollButton.setFont(new Font("Lucida Grande", Font.BOLD, 30));
rollButton.addActionListener(new RollHandler());

JPanel viewPanel = new JPanel();
viewPanel.setLayout(new GridLayout(1, 2, 10, 5));

setLayout(new BorderLayout());
add(rollButton, BorderLayout.NORTH);
add(viewPanel, BorderLayout.CENTER);

private class RollHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {

class Dice extends JPanel {
private String value;
private int spot_diam = 9;

private static Random roller = new Random();

public Dice() {
setPreferredSize(new Dimension(60, 60));

String getValue() {
return value;

void setValue(String value) {
this.value = value;

String roll() {
String val = Integer.toString(roller.nextInt(6) + 1);
return val;

public void paintComponents(Graphics g) {
Graphics2D eg = (Graphics2D)g;
eg.drawString(getValue(), 40, 120);

Answer Source
setPreferredSize(new Dimension(60, 60));

eg.drawString(getValue(), 40, 120);

What are the parameters of the drawstring() method? How can you paint something at 120 when its size is only 60?

public void paintComponents(Graphics g) {

Don't override paintComponents() (note the "s"). It should be paintComponent() you override.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download