2016-04-17 55 views
0

如果我使用的是GUI,並且有一個用戶可以鍵入的textField,然後該程序將鍵入,那麼在方法期間如何訪問KeyEvent? (keyEvent是當按下Enter鍵時 - >文本字段中的文本會產生響應)在方法中使用KeyEvent

例如:如果程序詢問用戶(通過方法)「你想吃這個蛋糕嗎? ?」然後用戶將輸入textField「yes」或「no」,根據響應,程序會給出另一個方法中的另一個問題或情況。

僞代碼:

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

@NullSaint:確實,一個不錯的答案。 1+ –

回答

3

解決方法:不使用的KeyEvent。如果您正在等待輸入按下JTextField中,您只需將該字段添加一個ActionListener,並在輸入press時進行響應。

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"); 
     } 
    } 
}); 

邊位:

  • 如果你希望你的GUI只除了明確定義條目的數量有限,如「是」和「否」,則不要使用一個JTextField但而是使用更適合於受控輸入的東西,例如JRadioButtons(添加到ButtonGroup),JSpinner或JComboBox。而不是警告用戶他們的輸入不正確,最好不要讓他們輸入錯誤的輸入。
  • 如果您想要響應文本組件中的按鍵(例如,JTextField,JTextArea ...),請將DocumentListener添加到文本組件的Document中。
  • 如果你想要過濾器輸入的文本爲int文本組件,例如,檢查文本的有效性,如果無效,則不允許它在字段中,然後將DocumentFilter添加到文本組件的Document中。
+0

謝謝!那麼爲了添加更多的方法,我只需要添加更多'@ Overrides'和我想要的方法? –

+0

@AtticusTrebmal:我不明白你的評論 - 增加更多的方法到什麼?到ActionListener?不,你不想這樣做。 –

+0

那麼我該如何添加另一種方法,如actionPerformed?就像我想用不同文本的相同方法一樣? –