2016-08-03 34 views
1

我正在研究一个基本的骰子滚轮GUI,并且我正试图在滚动时让数字在骰子上显示。目前一切看起来都正确,除了我的骰子是空白的。这里是我的代码:Graphics.paintComponents .drawString方法不会将数字放在我的骰子滚轮上

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); 
    } 
} 
+0

请注意,在上述代码中,“DiceRoller”**或**'ViewPanel'用于扩展'JPanel'并没有明显的原因。 –

回答

3
setPreferredSize(new Dimension(60, 60)); 


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

什么束带()方法的参数?当尺寸只有60时,你怎么能在120上画东西?

public void paintComponents(Graphics g) { 
    super.paintComponents(g); 

请勿重写paintComponents()(注意“s”)。应该是你覆盖的paintComponent()

2

对于自定义绘画,您应该覆盖JComponent.paintComponent()方法而不是Container.paintComponents()