JAVA初学者创建并掷骰子
我想创建一个掷骰子模拟器。这就是我到目前为止所得到的JAVA初学者创建并掷骰子,java,eclipse,graphics,Java,Eclipse,Graphics,我想创建一个掷骰子模拟器。这就是我到目前为止所得到的 public class RollDice { private static class rollDice extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); // custom draw code goes here } }
public class RollDice {
private static class rollDice extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// custom draw code goes here
}
}
public static void main(String[] args) {
JLabel message = new JLabel ("\nRoll the Die!\n", JLabel.CENTER);
message.setForeground(Color.BLACK);
message.setBackground(Color.WHITE);
message.setFont(new Font("Courier", Font.PLAIN, 25));
message.setOpaque(true);
JButton roll = new JButton("ROLL");
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(message, BorderLayout.NORTH);
content.add(roll, BorderLayout.SOUTH);
JFrame window = new JFrame("Roll Dice");
window.setContentPane(content);
window.setSize(250,300);
window.setLocation(300,300);
window.setVisible(true);
}
}
我有一个JFrame,JLabel,还有一个按钮,上面写着roll,简单的东西
我想弄明白的是如何在JPanel中创建两个骰子,以及如何使用math.Random
和图形在单击按钮“roll”时使其滚动
如果它尽可能简单,我将不胜感激,因为我在编程方面不是很先进,而且最近才开始。如果你能在给我答案之前尽可能详细地解释一下,我将不胜感激,这样我就有机会事先自己尝试弄清楚
谢谢 如果我们现在忽略了骰子的某种自定义绘图/动画,那么您的代码缺少一些功能元素:
- 为2个骰子的UI组件实例化对象
- 将这些组件添加到布局中(您可能还需要在此处创建嵌套布局对象,具体取决于您希望它们的定位方式)
- 定义
对象以生成掷骰子的随机数并更新骰子UI组件ActionListener
- 将
添加到滚动按钮ActionListener
- 像fd一样。也就是说,你需要模具的组件。让我们使用
JLabel
作为组件。它们可以这样安排:
+==============================+
| Roll the Die! |
| +---------+ +---------+ |
| | | | | |
| | dice1 | | dice2 | |
| | | | | |
| +---------+ +---------+ |
| +--------------------------+ |
| | ROLL | |
| +--------------------------+ |
+==============================+
您可以在标签上设置一个ImageIcon
(签出:),以便创建6个骰子不同位置的图像。按下按钮时,将生成一个随机数(介于1和6之间)(使用Math.random
)。每个数字代表一个图像。根据此编号设置标签的图像
要实现这一点,你需要一个。创建一个自定义的ActionListener
,如下所示(注意,我只做了一次):
每次按下按钮时,将调用ActionPerformed
方法并随机更改每个JLabel
的图标,模拟模具的滚动
要将自定义ActionListener
添加到按钮:
roll.addActionListener(new RollDiceActionListener(die));
ActionListener
需要修改表示骰子的Jlabel
s,因此不要忘记将其作为参数添加到侦听器的构造函数中
希望这有帮助。祝你好运 如果您有任何问题(在此处添加评论),请告诉我,我将完善我的答案。
roll.addActionListener(new RollDiceActionListener(die));