Benjamin
Benjamin

Reputation: 95

Copy&Paste to JavaFX TextArea and keep the Line break

I'm currently writing a Tool in JavaFX.

Therefor I need to copy some columns from Microsoft Excel using cmd + c, I then have the columns separated by tab in the clipboard.

e.g:

Column1    Column2   Column3
Value1   Value2   Value3
Value4   Value5   Value6

When I past the clipboard in an editor like Atom, they look exactly that way, but when I paste them into a TextArea, the line breaks are gone.

I need to do this, because I want to process the data from Excel using the Open CSV library.

Is there a way to keep the line breaks?

EDIT:

I just found out, if I use Clipboard.getSystemClipboard().getString() and than pass the String to my Open CSV handler, it works, but if I set the same string in a TextArea using textArea.setText(string) there are still no line breaks in the displayed Text.

Although it works now, I would like to user to paste the data into a TextArea, because it's a more common way than clicking a "paste&load" Button, and the user then also can check if all of the data was pasted.

Upvotes: 1

Views: 2174

Answers (1)

James_D
James_D

Reputation: 209684

I think the issue is that when Excel copies text to the System clipboard, it represents a line break as '\r', (ASCII 0xc) instead of the more standard '\n' (ASCII 0xa).

This is something of a hack, but if you do

    TextArea textArea = new TextArea(){
        @Override
        public void replaceText(IndexRange range, String text) {
            super.replaceText(range, text.replaceAll("\r", "\n"));
        }
        @Override
        public void replaceText(int start, int end, String text) {
            super.replaceText(start, end, text.replaceAll("\r", "\n"));
        }
        @Override
        public void replaceSelection(String replacement) {
            super.replaceSelection(replacement.replaceAll("\r", "\n"));
        }
    });

it will filter all the '\r' and replace them with '\n'.

Edit: here is a slightly cleaner version using a TextFormatter:

TextArea textArea = new TextArea();
UnaryOperator<Change> filter = c -> {
    c.setText(c.getText().replaceAll("\r", "\n"));
    return c ;
};
textField.setTextFormatter(new TextFormatter<>(filter));

Upvotes: 4

Related Questions