java 用图形用户界面编写双骰子游戏
时间: 2023-11-27 21:02:38 浏览: 94
好的,我可以给您提供一个简单的Java图形用户界面双骰子游戏代码示例。以下是一些参考代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DiceGame extends JFrame implements ActionListener {
private JPanel topPanel, bottomPanel;
private JLabel label1, label2, resultLabel;
private JButton button;
private JTextField textField1, textField2;
private int die1, die2, total;
public DiceGame() {
setTitle("双骰子游戏");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
label1 = new JLabel("骰子1: ");
textField1 = new JTextField(5);
topPanel.add(label1);
topPanel.add(textField1);
label2 = new JLabel("骰子2: ");
textField2 = new JTextField(5);
topPanel.add(label2);
topPanel.add(textField2);
bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout());
button = new JButton("掷骰子");
button.addActionListener(this);
bottomPanel.add(button);
resultLabel = new JLabel("结果: ");
bottomPanel.add(resultLabel);
add(topPanel, BorderLayout.NORTH);
add(bottomPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
die1 = (int) (Math.random() * 6) + 1;
die2 = (int) (Math.random() * 6) + 1;
total = die1 + die2;
textField1.setText("" + die1);
textField2.setText("" + die2);
resultLabel.setText("结果: " + total);
}
}
public static void main(String[] args) {
DiceGame game = new DiceGame();
}
}
```
在这个示例中,我们首先创建了一个包含输入骰子值和掷骰子按钮的顶部面板和一个显示结果的底部面板。当用户单击“掷骰子”按钮时,我们使用 Math.random() 方法来模拟掷骰子的结果,并将结果更新到文本字段和结果标签中。
希望这个示例有助于您开始编写您自己的Java图形用户界面双骰子游戏。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)