JavaFX textarea component error: ArrayIndexOutOfBoundsException

There was a problem with the gadget made before. From time to time, it reported that the array exceeded the boundary, but the specific code could not be located.

Take some time to solve it today.

The effect you want to achieve is like this: multiple threads display messages on the textarea in turn. In order to ensure real-time data update, you need to constantly refresh the textarea component.

The original code is like this

    public void refresh() {
        if(currentServerName == null) {
            //Refuse to refresh
            return;
        }
        setText("");
        appendText(LOG_MAP.getOrDefault(currentServerName, ""));
        setScrollTop(Double.MAX_VALUE);
        
    }

Directly refresh the data in the textarea in an external thread (a thread created by yourself).

After consulting the data, it is found that the container content must be modified in JavaFX’s own thread to ensure that no error will be reported. So wrap it with the platform. The modified code is as follows:

    public void refresh() {
        if(currentServerName == null) {
            //Refuse to refresh
            return;
        }
        setText("");
        appendText(LOG_MAP.getOrDefault(currentServerName, ""));
        setScrollTop(Double.MAX_VALUE);
        Platform.runLater(()->{
            setText("");
            appendText(LOG_MAP.getOrDefault(currentServerName, ""));
            setScrollTop(Double.MAX_VALUE);
        });
    }

Read More: