简体   繁体   English

Java Getter和Setter问题

[英]Java Getter and Setter Problem

Good day! 美好的一天!

I created two classes namely Setting and Game; 我创建了两个类,即设置和游戏; In my game access the Setting class first. 在我的游戏中首先访问Setting类。

In my setting class, I call the setter method from Game which is .setDifficulty. 在我的设置类中,我从Game调用setter方法,即.setDifficulty. and assign a value to it, example == 2. 并为其赋值,例如== 2。

public class Setting extends javax.swing.JDialog {

       public Setting (JFrame owner) {
                super(owner, true);
                initComponents();
                setSize(400, 250);
                setLocation(370, 250);
                getContentPane().setBackground(new Color(128, 201, 20));
            }
         private void btnOkMouseClicked(java.awt.event.MouseEvent evt) {                                   
            dispose();
            MainGame m2 = new MainGame(this);
            m2.setDifficulty(jComboBox1.getSelectedIndex());
        }           

Then I access My second CLass which is the game. 然后我访问我的第二个CLass,这是游戏。 But I cannot get the value of the difficultLvl outside the setter method. 但是我无法在setter方法之外获得hardLvl的值。 (See my comments on the code) (见我对代码的评论)

     public class Game extends javax.swing.JDialog {
        private int difficultLvl = 0;

        public Game(JFrame owner) {
            super(owner, true);
            initComponents();
            setSize(500, 500);
            setLocation(300, 120);
            getContentPane().setBackground(Color.getHSBColor(204, 204, 255));
            System.out.println(difficultLvl);  //SHOULD BE == 2, but == 0;
        }


        public void setDifficulty(int Difficulty) {
            this.difficultLvl = Difficulty;
            System.out.println(difficultLvl); == to 2 which is correct...
        }

The problem is that I cannot access the difficultLvl value outside the setter class... It returns to its default assigned value which on this case is 0. What am I doing wrong? 问题是我无法访问setter类之外的difficultyLvl值...它返回默认的赋值,在这种情况下为0.我做错了什么? How can access the value inside the setter method. 如何访问setter方法中的值。 I used this.difficultLvl but with no result. 我使用this.difficultLvl但没有结果。 I am just new in java... Please help! 我是java的新手...请帮忙! Your help would be highly appreciated. 非常感谢您的帮助。 Thank you. 谢谢。

Within the constructor of game the 'difficultLvl' member will be zero as that is what it is initialised to - no reason to expect it to be 2. Once constructed you use the setter method to set the value to 2; 在游戏的构造函数中,'difficultLvl'成员将为零,因为它是初始化的 - 没有理由期望它是2.一旦构造,你使用setter方法将值设置为2; from then on the value will be 2 until set to something else. 从那时起,该值将为2,直到设置为其他值。

If you were to add a getter method: 如果要添加getter方法:

public int getDifficulty() {
    return difficultLvl;
}

and call this you'll see the value. 并称之为你会看到价值。

I suspect you don't want to construct a new Game on every mouse click but instead keep one and just call the setter method on mouse click: 我怀疑你不想在每次鼠标点击时构建一个新的游戏,而是保留一个,只需在鼠标点击时调用setter方法:

   private  MainGame m2 = new MainGame(this);

   public Setting (JFrame owner) {
            super(owner, true);
            initComponents();
            setSize(400, 250);
            setLocation(370, 250);
            getContentPane().setBackground(new Color(128, 201, 20));
        }
     private void btnOkMouseClicked(java.awt.event.MouseEvent evt) {                                   
        m2.setDifficulty(jComboBox1.getSelectedIndex());
    }   

difficultLvl is an instance variable, so it has a value for each instance. difficultLvl是一个实例变量,因此它具有每个实例的值。 Every time you create a new instance of Game , it has its own diffucultLvl initialized to 0 . 每次创建Game的新实例时,它都会将自己的diffucultLvl初始化为0 If you set the difficultLvl in one Game , it doesn't change it for other Game instances and it doesn't affect future new Game instances. 如果设置difficultLvl在一个Game ,它不改变其用于其他Game情况下,它不会影响未来的新Game的实例。

private void btnOkMouseClicked(java.awt.event.MouseEvent evt) {                                   
        dispose();
        MainGame m2 = new MainGame(this);
        m2.setDifficulty(jComboBox1.getSelectedIndex());
}      

In this code, you create a game, MainGame m2 = new MainGame() , but it has default difficulty, which is what is printed in the constructor. 在这段代码中,您创建了一个游戏, MainGame m2 = new MainGame() ,但它有默认难度,即构造函数中打印的内容。 Next, you set its difficulty level (if you print the difficulty after this, it will be right). 接下来,您设置其难度级别(如果您在此之后打印难度,它将是正确的)。 Then game is thrown away: it goes out of scope - it was only a local variable. 然后游戏被抛弃:它超出了范围 - 它只是一个局部变量。

You are printing the value in the constructor. 您正在构造函数中打印值。 At that point the value will be 0. Its only after setDifficulty() is called that the value is set to 2. 此时,该值将为0.仅在调用setDifficulty()之后,该值才设置为2。

Its because you are first creating the MainGame object and the System.out.println is in the constructor. 这是因为您首先创建了MainGame对象,System.out.println位于构造函数中。 THEN you call the setter to change the value. 然后,您调用setter来更改值。 But the Constructor already printed the initial value (since it came first). 但构造函数已经打印了初始值(因为它是第一个)。

Sollution: The difficultyLevel needs to be a parameter of the Constructor for this to work. Sollution:难度级别需要是构造函数的参数才能使其工作。

Use a debugger and take a closer look. 使用调试器并仔细查看。 This is a very basic thing, so it is important to fully understand what is happening here. 这是一个非常基本的事情,因此充分了解这里发生的事情非常重要。

I see a couple of problems. 我看到了几个问题。

First are you sure to instantiate MainGame in the Setter class? 首先 ,您确定要在Setter类中实例化MainGame吗? Is it a subclass of Game or something different? 它是Game的子类还是其他不同的东西? If the code is correct, difficultLvl' in MainGame has nothing to do with difficultLvl in Game` - both are differen classes. 如果代码是正确的, difficultLvl' in MainGame has nothing to do with difficultLvl in Game` -都是differen类。

Second if you want the difficulty level for a game, either do it with the constructor: 其次,如果你想要游戏的难度级别,可以使用构造函数:

 public Game(int difficultyLevel) {
   this.difficultyLvl = difficultyLevel;
 }

or with the setter method, but then you set the value after creating the object and, because we all can't look into the future, you'll see nothing but the initial value with your actual code. 或者使用setter方法,但是创建对象之后设置了值并且因为我们都无法展望未来,所以除了实际代码的初始值之外什么都不会看到。

This line will call the constructor and create an object with difficultLvl = 0; 该行将调用构造函数并使用difficultLvl = 0创建一个对象;

MainGame m2 = new MainGame(this);

And after you call 你打电话之后

m2.setDifficulty(jComboBox1.getSelectedIndex());

then difficultLvl of m2 will be set to the selected index. 然后difficultLvlm2将被设置到所选择的索引。

You seem to create an instance of MainGame in your mouse click action handler which in turn get's garbage collected as soon as the method invocation finishes. 您似乎在鼠标单击操作处理程序中创建了一个MainGame实例,该处理程序在方法调用完成后立即收集垃圾。 So your value (=2) is lost since the object containing it is collected. 因此,您的值(= 2)将丢失,因为收集包含它的对象。 So on another click you create a new instance which has a value (=0) since u initialize it with 0. 因此,在另一次单击时,您将创建一个具有值(= 0)的新实例,因为您使用0初始化它。

private int difficultLvl = 0; private int difficultyLvl = 0;

I do not know much about what you want to do but it seems that you want to keep a handle pointing at the game object there somewhere in your app. 我不太了解你想做什么,但似乎你想要在你的应用程序的某个地方保持指向游戏对象的句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM