I'm trying to call a Getter from another class, and when I do, it returns and prints 0 every time. It generates a random number when you click the easyButton. After I click that button, it still shows zero after I call the getter with the enterInputButton. Here is the code. I have print statements to show that it doesn't work. I do this in other classes, and it works in my other small projects. I just dont understand why it returns 0 after I call it in the print statement, when I click the enterInputButton. Thank you so much! (Its my first time posting here)
public class UserInputPanel extends JPanel
{
private DifficultyPanel grabDiff;
private SpringLayout baseLayout;
private JTextField userGuessField;
private JButton enterInputButton;
private int userGuess;
//Class that needs the random Number
public UserInputPanel()
{
grabDiff = new DifficultyPanel();
baseLayout = new SpringLayout();
userGuessField = new JTextField(2);
enterInputButton = new JButton("Enter Guess");
buildPanel();
buildWindow();
buildListeners();
}
private void buildPanel()
{
setBackground(Color.RED);
setPreferredSize(new Dimension(200,200));
setLayout(baseLayout);
add(userGuessField);
add(enterInputButton);
}
private void buildWindow()
{
}
private void buildListeners()
{
enterInputButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent clicked)
{
parseInput();
System.out.println("MY INPUT " + userGuess);
//This line prints it to 0
System.out.println("GEN NUM : " + grabDiff.getSelectedNumber());
}
});
}
private void parseInput()
{
userGuess = Integer.parseInt(userGuessField.getText());
}
}
And here is the class that has the variable.
public class DifficultyPanel extends JPanel
{
private SpringLayout baseLayout;
private JButton easyButton;
private int selectedNumber;
public DifficultyPanel()
{
baseLayout = new SpringLayout();
easyButton = new JButton("Easy");
buildPanel();
buildListeners();
}
private void buildPanel()
{
setBackground(Color.BLUE);
setPreferredSize(new Dimension(200,200));
setLayout(baseLayout);
add(easyButton);
}
private void buildListeners()
{
easyButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
selectedNumber = (int) (Math.random() * 51);
System.out.println(selectedNumber);
}
});
}
public int getSelectedNumber()
{
System.out.println(selectedNumber);
return this.selectedNumber;
}
}