2015-09-27 183 views
1

我正在製作一個程序,其中用戶可以將字符串消息鍵入JTextArea組件,然後按回車以發送消息,然後清除JTextArea並將插入符號位置重置爲0.Java Swing如何重置JTextArea

JTextArea userChatBox = new JTextArea(); 
    userChatBox.addKeyListener(new KeyAdapter() { 
     @Override 
     public void keyPressed(KeyEvent e) { 
      if (e.getKeyCode()==10){ 
      //If key pressed is enter. 
       client.send(userChatBox.getText()); 
       userChatBox.setCaretPosition(0); 
       userChatBox.setText(""); 

      } 

     } 
    }); 
    userChatBox.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); 
    userChatBox.setTabSize(4); 
    userChatBox.setLineWrap(true); 
    userChatBox.setForeground(UIManager.getColor("ColorChooser.foreground")); 
    userChatBox.setFont(new Font("DejaVu Serif", Font.PLAIN, 12)); 
    userChatBox.setBackground(Color.WHITE); 
    userChatBox.setBounds(10, 255, 400, 80); 
    frmChatClient.getContentPane().add(userChatBox); 

但是,當用戶按Enter時,JTextArea會將其註冊爲回車並輸入新行。即使在userChatBox.setCaretPosition(0);之後,插入符號也出現在第二行,隨後從JTextArea發送的任何字符串都將包含一個空行。我也嘗試設置選擇開始和結束沒有用。

+3

我認爲[這個答案](http://stackoverflow.com/a/32148769/4857909)會解決這個問題。 –

回答

4

作爲@luxxminer表示問題是事件首先發生在文本附加到jtextarea.if你可以消耗事件,然後新行不會追加。

所以你可以使用event.consume();方法

if (e.getKeyCode()==10){ 

    //If key pressed is enter. 
     client.send(userChatBox.getText()); 
     userChatBox.setCaretPosition(0); 
     userChatBox.setText(""); 
     e.consume(); 
} 
+0

請有真正的理由使用,爲什麼要使用JTextComponents的KeyListener,也許10 == ENTER,這是一個new_line作爲UIManager中的JTextArea的KeyBindings – mKorbel