Java swing中的keyListener使用事例


最近在學習Java swing,寫了一個域內聊天室,實現用戶登錄ip,端口號之后,進入聊天窗口聊天:

通過菜單條增加了幾個功能,邊框,字體,顏色和文件傳輸。風格里的樣式都可以通過自己選擇來設置。

 

 

介紹以上。

但在實現發送的功能時,想要增加默認回車發送消息功能:

原來的send按鈕監聽事件代碼:

private class sendListener implements ActionListener{
  @Override
  public void actionPerformed(ActionEvent e) {
  String str = editMsg.getText();
    try {
      DataOutputStream dos = new DataOutputStream(s.getOutputStream());
      if(str.equals(" ") || str.equals("") || str==null){
        JOptionPane.showMessageDialog(null, "輸入不能為空,請重新輸入!", "提示",JOptionPane.OK_OPTION);
      }else{
        dos.writeUTF(str);
      }
      dos.flush();
      editMsg.setText("");
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }

中間的用戶不可編輯的消息顯示區,增加一個鍵盤監聽事件:

editMsg.addKeyListener(new KeyListener() {

  @Override
  public void keyTyped(KeyEvent key1) {
    return;
  }

  @Override
  public void keyReleased(KeyEvent key2) {
    int code = key2.getKeyCode();
    if(code==10){
      editMsg.setText("");
    }
    return;
  }

  @Override
  public void keyPressed(KeyEvent key3) {
    int code=key3.getKeyCode();
      if(code==10){
        String str = editMsg.getText();
      try {
          DataOutputStream dos = new DataOutputStream(s.getOutputStream());
          if(str.equals(" ") || str.equals("") || str==null){
            JOptionPane.showMessageDialog(null, "輸入不能為空,請重新輸入", "提示",JOptionPane.OK_OPTION);
          }else{
            dos.writeUTF(str);
          }
          dos.flush();
          editMsg.setText("");
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
      return;
    }
  });

 keyTyped為按鍵敲擊事件,keyReleased為按鍵按下之后釋放時的方法,keyPressed為按鈕按下之后,釋放之前的方法。

在keyPRessed方法中,每按一次按鍵時,先獲取keyCode編碼,確定回車的ASCII碼值,再來判斷是否發送消息。

思路是正確的,但在此出現了一個問題,每次回車發送消息之后,會有一個自動換行的操作,這也導致判斷消息為空的代碼失效。

解決辦法:在keyReleased的方法中同樣再判斷一次回車的ASCII碼值,再次清空輸入框,問題得到解決。

 

總結:在鍵盤的監聽中,主要通過判斷按鍵的執行順序以及按鍵的ASCII值來采取對應操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM