如何使用按钮将布尔值从 false 更改为 true

时间:2021-04-29 20:54:33

标签: java swing

我为 while 循环创建了一个布尔值以使其在布尔值等于 true 时运行,我想让播放按钮使 boolean = true 触发 while 循环并运行游戏。但这由于某种原因不起作用。

有人可以帮忙制作boolean gameRunning = true;吗?我只是不知道如何将其值从 false 更改为 true

我尝试使用 atomic booleans 但没有用

package panda.org;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math;
import java.util.concurrent.atomic.AtomicBoolean;

public class NumberGame implements ActionListener{

    JFrame frame;
    JLabel rules;
    JLabel rulesText;
    JLabel rulesText2;
    JButton play;
    JButton exit;

    Font myFont = new Font("Serif Plain", Font.BOLD, 15);

    NumberGame() {

        frame = new JFrame("NumberGame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500);
        frame.setLocationRelativeTo(null);
        frame.setLayout(null);
        frame.setResizable(true);
        Image icon = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Gaming MSI\\Pictures\\Saved Pictures\\download (1).png");
        frame.setIconImage(icon);

        rules = new JLabel("Rules: ");
        rules.setFont(myFont);
        rules.setBounds(50, 100, 100, 75);

        rulesText = new JLabel("We will pick a random number in the range of 1 -> 50.");
        rulesText.setBounds(100, 100, 315, 75);

        rulesText2 = new JLabel("Your job is to guess that number!");
        rulesText2.setBounds(100, 120, 315, 75);

        play = new JButton("Play");
        play.setBounds(150, 300, 100, 75);

        boolean gameRunning = false;

        play.addActionListener(e -> {
            gameRunning = true;
        });

        while(gameRunning = true) {

            JLabel label = new JLabel("Guess the number from 1 till 50");
            label.setFont(myFont);
            label.setBounds(150, 75, 315, 75);

            JLabel hints = new JLabel("");
            hints.setBounds(150, 180, 1000, 100);

            JLabel hints2 = new JLabel("");
            hints2.setBounds(150, 200, 1000, 100);

            JTextField text = new JTextField();
            text.setBounds(250, 150, 100, 25);

            JButton check = new JButton("Check");
            check.setBounds(150, 150, 75, 25);

            double randomDouble = Math.random();
            randomDouble = randomDouble * 50 + 1;

            double randomDouble2 = Math.random();
            randomDouble2 = randomDouble2 * (15 - 5 + 1) + 5 ;

            double randomDouble3 = Math.random();
            randomDouble3 = randomDouble3 * (15 - 5 + 1) + 5 ;

            int randomHint = (int) randomDouble2;
            int randomHint2 = (int) randomDouble3;
            int randomInt = (int) randomDouble;

            System.out.println("nb: " + randomInt);
            System.out.println("hint: " + randomHint);
            System.out.println("hint2: " + randomHint2);

            JLabel status = new JLabel("");
            status.setBounds(150, 160, 1000, 100);

            JLabel closeness = new JLabel("");
            closeness.setBounds(150, 220, 1000, 100);
            closeness.setForeground(Color.blue);

            final int[] failedAttempts = {0};

            check.addActionListener(e1 -> {

                String nb = text.getText();
                int change = Integer.parseInt(nb);

                frame.add(status);

                if (randomInt == change) {
                    status.setText("You chose the correct number!");
                    status.setForeground(Color.green);

                    hints.setText("");
                    hints2.setText("");
                }
                if (randomInt > change) {

                    closeness.setText("Your answer is smaller than the correct answer");

                }
                if (randomInt < change) {

                    closeness.setText("Your answer is larger than the correct answer");

                }
                if (randomInt != change) {
                    status.setText("Wrong choice! Try again.");
                    status.setForeground(Color.red);
                    failedAttempts[0]++;

                    if (failedAttempts[0] == 3) {

                        int plus = randomInt + randomHint;
                        int minus = randomInt - randomHint2;

                        hints.setText("Hint: I see you are struggling, here is a low range to make it easier!");
                        hints2.setText("The lowered range is from " + plus + " to " + minus);
                    }
                }
            });

            rules.setText("");
            rulesText.setText("");
            rulesText2.setText("");

            frame.add(hints);
            frame.add(hints2);
            frame.add(label);
            frame.add(check);
            frame.add(closeness);
            frame.add(text);
        }

        exit = new JButton("Exit");
        exit.setBounds(350, 300, 100, 75);
        exit.addActionListener(e -> {

            int result = JOptionPane.showConfirmDialog(frame,"Are you sure want to exit?", "Exit",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if(result == JOptionPane.YES_OPTION){
                System.exit(0);
                }
        });

        frame.add(play);
        frame.add(exit);
        frame.add(rules);
        frame.add(rulesText);
        frame.add(rulesText2);

        frame.setVisible(true);
    }

    public static void main(String[] args) {

        NumberGame number = new NumberGame();

    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}


2 个答案:

答案 0 :(得分:2)

您仍在考虑控制台应用程序,Swing 旨在处理事件...

  • 用户按下了按钮?一个事件
  • 某个计时器在后台触发了什么?一个事件
  • 用户输入了什么?一个事件

因此,考虑到上述情况,您不能在这里指望您的代码:

play.addActionListener(e -> {
    gameRunning = true;
});

while(gameRunning = true) {
    ...
}

按该顺序执行,因为您无法控制用户何时按下按钮,可能是 2 秒后,也可能是 2 小时后

为此,您可能需要将 while 循环移动到一个方法,并且当用户按下 play 按钮时,您需要更改 gameRunning = true 然后调用它其他方法,像这样:

public void runGame() {
    while(gameRunning) {
        // Your code here
    }
}

play.addActionListener(e -> {
    if (!gameRunning) { //This validation is needed otherwise if you press the button multiple times you'll have multiple loops running
        gameRunning = true;
        runGame();
    }
});

这样,在用户按下 play 按钮之前,您不会开始游戏。

请注意我是如何在没有 while(gameRunning) 的情况下编写 ==,如上面的评论中所述,如果您有 gameRunning = true,则在使用 { {1}} 变量,您可以像这样简单地编写它们,这样可以减少出现类似拼写错误的可能性。

  • booleanif(true)
  • 相同
  • if (true == true)if(!false)
  • 相同
  • if (false == false)if(false)
  • 相同

正如我在我的 previous answer 中提到的,避免使用 if (true == false)null-layout,为什么您实施 setBounds 而从不使用它?它是空的,所以只需删除 ActionListener

答案 1 :(得分:0)

您不能在 lambda 函数中更改局部变量的值。正如我确定编译器告诉您的那样,它们需要是 final 或有效 final 的,这意味着它们只被分配一次。

解决方案是使用一种可以保存布尔值的类型,并改为更改它所保存的值。

    AtomicBoolean gameRunning = new AtomicBoolean(false);

    play.addActionListener(e -> {
        gameRunning.set(true);
    });

    ...

    while(gameRunning.get()) {
    }