[英]KeyBinding for getting text from JTextField
我有一個JTextField
,它將在用戶提交輸入之前保存用戶的輸入(如果願意的話,就像控制台Scanner
對象一樣)。 我的主類有一種從用戶那里獲取輸入的方法。 使用Scanner
對象,這很容易做到: scannerObject.nextLine()
。 通過此JTextField
,我決定使用“鍵綁定”來確定何時按下Enter鍵,以便“提交” JTextField
的內容。 我設置了鍵綁定沒有問題,但是我無法弄清楚如何讓主程序等到按下Enter鍵以查找文本。 如果使用循環,則程序將卡住,無法注冊按鍵。
這是一種嘗試從JTextField
獲取輸入的方法:
public static String getStrInput() {
// Request input
display.print(">> ");
needInput = true;
nextInput = "";
// Wait until a string is input from the text field
while (nextInput.isEmpty()); // Wait
needInput = false;
return nextInput;
}
這是在我的鍵綁定類中按下Enter鍵時的事件處理程序:
private class SubmitAction extends AbstractAction implements ActionListener {
/**
* Makes Java happy.
*/
private static final long serialVersionUID = 1L;
/* -- Constructor -- */
public SubmitAction() {
}
/* -- Method -- */
@Override
public void actionPerformed(ActionEvent e) {
if (Game.needInput())
Game.submitTextField();
}
}
注意: submitTextField()
方法所做的只是調用textField.getText()
方法,並將nextInput
字段(請參閱我的第一個方法)設置為返回的String。
應該發生的是應該注冊輸入請求(這是needInput = true
行),然后在按下Enter鍵時,Key Binding類應該提交文本字段(因為現在出現了Game.needInput()
條件Game.needInput()
返回true)。 但是,在我的getStrInput()
方法中,程序被卡在while (nextInput.isEmpty());
環。 我認為會發生這種情況,但是我不知道如何讓主程序等待鍵綁定的事件處理程序讓文本字段提交其內容。
如果這根本沒有道理,或者我需要公開更多代碼,我將很樂於闡述。 我整天都在研究這個小問題,目的只是為了發現沮喪。
通過此JTextField,我決定使用“鍵綁定”來確定何時按下Enter鍵以“提交” JTextField的內容。
實際上,您應該只在文本字段中添加一個ActionListener即可。 當按下Enter鍵時,將調用ActionListener。
如果要提示並等待輸入文本,則應使用JOptionPane
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.