Using the method below, I am trapping the VK_ENTER key event to gather the text in a default JTextArea, process it, and then empty the JTextArea. I noticed that the caret did not reset to the upper left but to the first column of the second row instead. No matter what I have tried, I cannot seem to convince the caret to go back to the upper left corner (it's original starting position). You can see my attempts to understand where the caret believes that it is. There is definitely an empty line in place after the Enter key is trapped for the first time.
The reason I use JTextArea is because my text to process may be up to 256 bytes long, so a JTextField is cumbersome.
private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_ENTER){
try {
sendCommand("hf", "ab4mw", jTextArea2.getText().trim());
jTextArea1.append(TX + jTextArea2.getText().trim() + nl);
jTextArea2.setText("");
System.out.println("carat: " + jTextArea2.getCaretPosition());
System.out.println("length: " + jTextArea2.getText().length());
jTextArea2.setCaretPosition(0);
//jTextArea2.moveCaretPosition(0);
System.out.println("line: " + jTextArea2.getLineCount());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output of the first use of this method: carat: 0 length: 0 line: 1
Output of the second use of this method: carat: 0 length: 0 line: 1
...ad infinitum.
Am I missing something simple here?