java - 硬币翻转模拟:计数正面/反面
问题描述
我正在尝试使用 Java 和窗口构建器来模拟投币器。当按下该按钮时,我有一个名为“翻转”的按钮,硬币图像会根据我创建的随机生成器生成的数字而变化。
我现在正试图找出一种方法来显示硬币在各自的JTextFields
. 我正在考虑使用计数器,但我正在努力将其更新到文本字段中,到目前为止,它只表明我将每个硬币都翻转了一次。
我对编程非常陌生,因此非常感谢任何建议或指导。
// this button flips the coin
btnFlip = new JButton("Flip");
btnFlip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int headCounter = 0;
int tails = 0;
// this implements the random flip of the coin when the checkbox Run Multiple
// flips is unchecked
if (chckbxNewCheckBox.isSelected() == false) {
Random r = new Random();
int flipper = r.nextInt(2);
if (flipper == 1) {
lblImages.setIcon(new ImageIcon(FinalPrep.class.getResource("/finalPrep/heads.png")));
textFieldHeads.setText(String.valueOf(headCounter));
} else {
lblImages.setIcon(new ImageIcon(FinalPrep.class.getResource("/finalPrep/tails.png")));
textFieldTails.setText(String.valueOf(tails));
}
}
}
});
btnFlip.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_1.add(btnFlip);
解决方案
您必须创建类似 2 层的东西。一个包含窗口本身和标题(把它想象成一个受体)然后你必须创建另一个包含按钮和文本字段的“层”。像这样的东西:
import javax.swing.*;
public class MyFrame extends JFrame {
private JPanel panel;
private JTextField textField;
private JButton button;
public MyFrame(){
panel = new JPanel(); //Step 1. Creation of a receptor
tfCount = new JTextField(10); //Step 2.
button = new JButton("Press Me"); //Creation of buttons & textfields.
panel.add(tfCount); //Step 3.
panel.add(button); //Add those graphics to the receptor
this.setContentPane(panel); //Step 4 Adjust the receptor to the object
this.setVisible(true);
this.setSize(400, 400);
this.setTitle("My 1st GUI!");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
(很抱歉随机示例,但您没有发布任何代码示例,所以我试图尽我所能解释)
然后你应该根据生成的数字放置一个“标志”,例如:
boolean flag = true; //Flag
int counter = 0; //The counter for the heads
int x; //The number you received from the generator
int counter_b; //The counter for the tails
if(x%2 == 0){ //If the number is even
flag = false; // You set down the flag
counter++; //And counter raises its value
}
else
counter_b++;
tfCount.setEditable(true); //This makes your textfield editable
tfCount.setText(String.valueOf(counter)); //And this prints the counter's value
请记住,尾部和头部的计数器只是您了解如何使用“标志”的示例。我希望我能够帮助你,因为我也是新手!!:)
推荐阅读
- php - PHP:从文件中获取 JSON 数据,处理数据并将其保存到新的 JSON 文件中
- python - 如何修复“_tkinter.TclError:无法打开“Island1.png”:没有这样的文件或目录”错误?
- javascript - 在 Vue js 中自动按名称对 API 列表进行排序
- javascript - 将 JSON 调用中的数据插入页面
- c - C 中的复合运算符 (+=) 和 &&,奇怪的值
- python - 如何在不按名称获取根节点的情况下读取它们的属性?
- c - SIMD 搜索最后一个峰值后的低谷
- reactjs - 将多个属性传递给组件
- javascript - 我想在javascript中捕获选中复选框的所有标签
- java - 意外的 Java Maven 项目命名