[英]How do I add a button listener in Java?
我想在 Java 中添加一個按鈕偵聽器,以便當用戶只需按下enter
時,按鈕就會被按下。
我嘗試將此動作偵聽器添加到我創建的按鈕中:
String guessText = txtGuess.getText();
JTextField txtGuess = new JTextField();
txtGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkGuess();
}
});
這是整個 function:
public void checkGuess() {
String guessText = txtGuess.getText();
JTextField txtGuess = new JTextField();
txtGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkGuess();
}
});
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber)
message = guess + " is too low. Try again.";
else if (guess > theNumber)
message = guess + " is too high. Try again.";
else {
message = guess + " is correct. Let's play again!";
newGame();
}
lblOutput.setText(message);
}
但是,當我的 gui 出現並在輸入輸入后按“輸入”時,什么也沒有發生。 我必須實際單擊“ Guess
”按鈕,這是我試圖避免的!
這是我創建的 window:
我希望用戶輸入一個數字並按 Enter 鍵,然后單擊Guess
按鈕。 幫助? 我究竟做錯了什么?
所以我假設你想保留在按下輸入時應用相同代碼的權利,就像按下按鈕一樣。
為此,我將向按鈕添加一個 ActionListener 以及向文本字段添加一個 ActionListener。 然后讓這兩個 ActionListener 觸發一個返回輸入,該輸入將根據隨機生成的數字進行檢查。
JTextField 的 ActionListener 方法在按下回車鍵時自然觸發。
目前,您有一個方法可以返回並檢查輸入文本並創建一個新的文本字段。 您似乎以遞歸方式執行此操作,而不是您可以簡單地使用類似於以下的方法:
private JTextField txtGuess;
private void initialiseTextField(){//Initialises a textField to be used for all inputs.
txtGuess = new JTextField();
txtGuess.addActionListener(){
public void actionPerformed(ActionEvent e) {
checkGuess();
}
}
}
public void checkGuess() {
String guessText = txtGuess.getText();
txtGuess.setText("");//Empties the contents of the text field.
String message = "";
int guess = Integer.parseInt(guessText);
if (guess < theNumber)
message = guess + " is too low. Try again.";
else if (guess > theNumber)
message = guess + " is too high. Try again.";
else {
message = guess + " is correct. Let's play again!";
newGame();
}
lblOutput.setText(message);
}
為了使其工作,您需要將 txtGuess 聲明為 class 的屬性。 您可以使用以下命令執行此操作:
private JTextField txtGuess;
我將它設置為私有,但如果它是公開的,它應該可以工作。
initialiseTextField 方法初始化整個 class 的文本字段條件,這意味着每次輸入文本時都不會創建新的 JTextField。
希望這應該可以解決您的問題。 問我是否需要更多幫助。
注意:我只提供了如何使用回車鍵檢查輸入的示例,您仍然需要自己創建按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.