Good day!
I created two classes namely Setting and Game; In my game access the Setting class first.
In my setting class, I call the setter method from Game which is .setDifficulty. and assign a value to it, example == 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. But I cannot get the value of the difficultLvl outside the setter method. (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? How can access the value inside the setter method. I used this.difficultLvl but with no result. I am just new in java… Please help! Your help would be highly appreciated.
Thank you.
I see a couple of problems.
First are you sure to instantiate
MainGamein theSetterclass? Is it a subclass ofGameor something different? If the code is correct,difficultLvl' inMainGamehas nothing to do withdifficultLvlinGame` – both are differen classes.Second if you want the difficulty level for a game, either do it with the constructor:
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.