Issue
Platform: Intellij IDEA
Language: JavaFX
I would like to be able to select a line of text where the cursor lies. Similar to SQL Developer, I have a textarea that allows multiples lines of input or queries. It is nice to be able to use the textarea as a query bank while testing queries.
Using the txtOutput.getCaretPosition(), I would like to get the current integer index of the line where the cursor resides and then be able to select all of the text that is within that same line with the same keyboard shortcut as SQL Developer (Ctrl + Enter). Using the .selectForward() or .selectBackward() will not work if there are multiple lines.
Any help or suggestions as to how to limit the selection of text to one line or select text up until a specific character (e.g. ";") would be much appreciated.
public void executeEvent(KeyEvent event) {
//int cursorLine = txtInput.getCaretPosition();
if (event.isControlDown() == true && event.getCode() == KeyCode.ENTER) {
//select line of text where integer equals cursorLine
//txtInput.selectBackward();
//txtInput.selectForward();
}
}
Solution
Just search the text for the relevant delimiting character (e.g. a newline character), and select the relevant portion. The only thing you have to be careful of here is if the user selects the last line, in which case there will be subsequent newline character:
int caretPos = txtInput.getCaretPosition();
int previousNewline = txtInput.getText().lastIndexOf('\n', caretPos);
int nextNewline = txtInput.getText().indexOf('\n', caretPos);
if (nextNewline == -1) nextNewline = txtInput.getText().length();
txtInput.selectRange(previousNewLine + 1, nextNewLine);
Answered By - James_D
Answer Checked By - Mary Flores (JavaFixing Volunteer)