JTextArea after pressing enter

I am creating a chat for java using sockets. My problem is that in the frame for the user, when I first got into Enter, Caret goes to the next line, and after that I need to press back, because otherwise an empty phrase is sent with the sentence that I wrote. I use KeyListener to press enter, and I entered the following code into the KeyPressed function.

if(arg0.getKeyCode()==10) { System.out.println("Bika sto enter\n"); String toserver = ClientText.text2.getText(); try { if(toserver.equals("close it")) { ClientText.clientSocket.close(); } ClientText.text2.moveCaretPosition(ClientText.text2.getSelectionStart()); ClientText.text2.setCaretPosition(0); ClientText.text2.setText(""); ClientText.outToServer.writeBytes(toserver+'\n'); //ClientText.outToServer.writeUTF(toserver+'\n'); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

The fact is that this only works after the first use of the chat. For example, I sent something, and the carriage moves to the next line if I press Enter. Then, if I write something and clicking, enter the carriage, which goes to the beginning of the second line! So is there an empty first line that I have to erase every time with any help on this? Thanks

+4
source share
1 answer

I'm not sure what your GUI looks like, but I would use javax.swing.JTextField instead of JTextArea. If you want to use JTextArea (for example, to allow multiline messages), and you cannot make part of the input to send work, I would resort to using KeyListener as an input key, like a normal computer (if all else fails).

Here is what I mean:

 import java.awt.event.*; import javax.swing.JTextArea; //or JTextField public class KeyInput implements KeyListener{ private JTextArea ta; //or JTextField public KeyInput(JTextArea ta){ //or JTextField this.ta = ta; } public void keyPressed(KeyEvent e){ if(e.getKeyCode() == KeyEvent.VK_ENTER){ //code to send message goes here }else{ ta.append("\n"+e.getKeyChar()); } } //keyReleased(KeyEvent) and keyTyped(KeyEvent) methods go here, need no content } 

Remember that if you use JTextArea, be sure to place it in JScrollPane.
IMPORTANT : in your client class, be sure to add ta.setEditable(false) , in which ta is the variable name of your JTextArea (again, you can replace JTextField, in which case you do not need JScrollPane).

Hope this helps.

0
source

Source: https://habr.com/ru/post/1495520/


All Articles