javaswingjtextareacaret

Why does the text change after I set the Caret position for JTextArea?


I'm creating a program which uses a JTextArea, and when I try to change the caret position it goes from this:

hello
Hello there
-
|

Code:

public void executeCommand(String cmdName){
    Boolean cmdFound = false;
    
    for(int i = 0; i < cmdNames.size(); i++){
        if(cmdNames.get(i).toLowerCase().equals(cmdName.toLowerCase())){
            cmdFound = true;
            cmds.get(cmdName).actionPerformed(new ActionEvent(this, 0, null));
            Config.cmdln.println("-");
            Config.cmdln.setCaretPosition(Config.cmdln.getText().length()); //part that changes
            break;
        }
    }
    
    if(!cmdFound){
        Terminal.cmdln.println("Command " + "\"" + cmdName + "\"" + " not found.");
    }

to this:

hello
Hello there

|- 

Code:

public void executeCommand(String cmdName){
    Boolean cmdFound = false;
    
    for(int i = 0; i < cmdNames.size(); i++){
        if(cmdNames.get(i).toLowerCase().equals(cmdName.toLowerCase())){
            cmdFound = true;
            cmds.get(cmdName).actionPerformed(new ActionEvent(this, 0, null));
            Config.cmdln.println("-");
            Config.cmdln.setCaretPosition(Config.cmdln.getText().length() - 1); //part that changes
            break;
        }
    }
    
    if(!cmdFound){
        Terminal.cmdln.println("Command " + "\"" + cmdName + "\"" + " not found.");
    }

This is the output I want:

hello
Hello there
-|

Note: the "|" represents the caret

Let me know if you need any more code.


Solution

  • You can simply replace Config.cmdln.getText().length() - 1 by Config.cmdln.getText().length() + 1 (the - has changed to the +).

    This is possible since you are adding a character with the println() line before.