簡體   English   中英

為打字游戲添加 ActionListener

[英]Adding ActionListener for a typing game

一直在查看有關將ActionListenerJTextField結合使用的大量文檔,並且看到出於類似原因提出的許多其他問題,但我似乎無法將解決方案應用於我的問題。 我需要的基本前提是屏幕上會有一個文本字段供用戶輸入單詞。

我希望計時器在按下某個按鍵后開始在后台運行。 (最好輸入或空格鍵)然后當整個句子寫完時計時器應該停止。 到目前為止,我還沒有很幸運地通過按鍵來啟動一個事件。 下面是一些實際上不起作用的代碼,我可以成功地創建帶有文本框的框架我只是無法讓動作偵聽器為我想要的目的工作。

input = new JTextField();
input.setBounds(10, 150, 780, 35);
panel.add(input);
input.addActionListener(new ActionListener());

public void actionPerformed(ActionEvent e) {
}

沒有在actionPerformed方法中添加任何內容,因為我運行的所有測試都不成功。 不要求完整的代碼,但指向正確方向的指針可能會有所幫助。 是的,我已經閱讀了有關如何使用addActionListener()的文檔,但我無法將其應用於我想做的事情。

您需要一個 KeyListener,而不是 ActionListener。

實現 KeyListener,然后在方法 keyPressed(KeyEvent name) 中,使用switchif語句鍵入 e.getKeyCode。 例如(偽代碼):

 javax.swing.JTextField input=null;
 javax.swing.JPanel panel=null;
 public class X implements java.awt.event.KeyListener{

 input = new javax.swing.JTextField();
 input.setBounds(10, 150, 780, 35);

 panel.add(input);
 input.addActionListener(new ActionListener());
 input.addKeyListener(this);
 public void keyPressed(java.awt.event.KeyEvent e){
 if(e.getKeyCode==e.VK_W){
 //Enter code here 
 }}public void actionPerformed(ActionEvent e) {
 //then upon enter the timer stops
 }


 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM