如果我使用的是GUI并且有一个用户输入的textField,然后程序会输回,那么在方法中如何访问KeyEvent? (keyEvent将在按下Enter键时显示 - > textfield中的文本将生成响应)
例如:如果程序询问用户(通过方法)"你想吃这块蛋糕吗?"然后用户输入textField" yes"或"不"根据反应,该计划将以另一种方法提出另一个问题或情况。
伪代码:
public void cakeQuestion(){
eventList.setText(eventList.getText() + "\nWould You Like To Eat This Cake?"); //eventList is a textArea
//***KeyEvent takes place, perhaps saving the user's input as a String called resposne
if(response.equals("yes"){
eatCake //eatCake is another method with another situation
}
else if(response.equals("no"){
eatPie //eatPie is another method with another situation
}
else{eventList.setText(eventList.getText() + "\nI don't understand that response");}
}
答案 0 :(得分:3)
解决方案:您不使用KeyEvent。如果你正在等待按下JTextField中的输入,你只需给该字段一个ActionListener,这将在回车时响应。
myTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String response = e.getActionCommand();
if(response.equals("yes"){
eatCake(); //eatCake is another method with another situation
}
else if(response.equals("no"){
eatPie(); //eatPie is another method with another situation
} else{
eventList.setText(eventList.getText() + "\nI don't understand that response");
}
}
});
边位: