我想從另一個類調用Getter,當我這樣做時,它每次都返回並打印0。 當您點擊easyButton時,它會生成一個隨機數。在我點擊該按鈕之後,在使用enterInputButton調用getter後,它仍然顯示爲零。 這是代碼。 我有打印語句顯示它不起作用。我在其他課程中這樣做,並且在我的其他小型項目中工作。 我只是不明白爲什麼它在打印語句中調用它時返回0,當我單擊enterInputButton時。 非常感謝! (它的我第一次在這裏張貼)Getter返回0 [Java]
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());
}
}
這裏是具有變量的類。
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;
}
}
由於在其他項目中的「它」的作品 - 什麼你有不同的做法嗎?數字何時更改,即點擊了「easyButton」? –
我沒看見你把它放在任何地方。您將grabDiff作爲一個新對象,只是調用get select number – logger
'selectedNumber'正在'easyButton'的'ActionListener'中設置。只要調用這些方法並按正確的順序按下按鈕,'selectedNumber'字段就應該設置成某種東西。 – khelwood