在lambda表达式中使用的变量应该是final还是有效的final?

时间:2018-10-15 11:02:40

标签: java swing

我正尝试创建一个小游戏作为项目,以帮助自己学习编码。基本上我想有2个按钮。其中一个将生成一个新的随机数,另一个将允许您猜测该数字。我遇到的错误是我无法创建一个在单击按钮时将生成新数字的Actionlistener,因为它不允许我在Lambda表达式本身之外更改int。

我们非常感谢您的帮助!

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

/**
 * Created by Alex on 10/15/2018.
 */
public class NumberGame
{

    public static void main(String[] args) {
        int gamesNumber = 0;
        int myNumber;

        JFrame gameGUI = new JFrame("Number guess game");
        gameGUI.setSize(400,400);
        gameGUI.setVisible(true);
        gameGUI.setLayout(null);
        gameGUI.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //Create components for GUI
        JLabel AmIRight = new JLabel();
        JLabel generateNumber = new JLabel();
        JButton chooseNumber = new JButton("Choose");

        JButton generateNumber2 = new JButton("Generate");
        generateNumber2.addActionListener(e -> {
            Random rand = new Random();
            int number = rand.nextInt(10) + 1;
            gamesNumber = number;
            System.out.println(gamesNumber);
        });

        //Calling Methods
        //gamesNumber = GenerateRandomNumber();

        //Adding components to GUI
        gameGUI.add(AmIRight);
        gameGUI.add(chooseNumber);
        gameGUI.add(generateNumber);
        gameGUI.add(generateNumber2);

        //Give components properties
        AmIRight.setBounds(40,100,300,300);
        AmIRight.setText("Push the button below to choose a number to guess!");
        generateNumber.setBounds(60,-100,300,300);
        generateNumber.setText("Push the button below to Generate a number!");
        chooseNumber.setBounds(130,270,100,50);
        generateNumber2.setBounds(130,70,100,50);

    }


}

1 个答案:

答案 0 :(得分:0)

您需要将gamesNumber定义为成员字段

public class NumberGame
{
    private static int gamesNumber = 0;
    public static void main(String[] args) {
        int myNumber;

        JFrame gameGUI = new JFrame("Number guess game");