首页 > 解决方案 > 硬币翻转模拟:计数正面/反面

问题描述

我正在尝试使用 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);

标签: javaswingjbuttonjtextfield

解决方案


您必须创建类似 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

请记住,尾部和头部的计数器只是您了解如何使用“标志”的示例。我希望我能够帮助你,因为我也是新手!!:)


推荐阅读