flybonzai flybonzai - 3 months ago 9
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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack(); //To set frame so contents are at or above preferred size.
frame.setVisible(true);
}
}

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));
viewPanel.add(dice1);
viewPanel.add(dice2);

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

private class RollHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
dice1.roll();
dice2.roll();
}
}
}

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

private static Random roller = new Random();

public Dice() {
setBackground(Color.WHITE);
setPreferredSize(new Dimension(60, 60));
roll();
}

String getValue() {
return value;
}

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

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

@Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
Graphics2D eg = (Graphics2D)g;
eg.setColor(Color.BLACK);
eg.drawString(getValue(), 40, 120);
}
}

Answer
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) {
    super.paintComponents(g);

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

Comments