views:

61

answers:

2

Hi! Here is a challenging question!

Let me first tell you my scenario how am i implementing a solution to a problem.

I am reading a log file and displaying it on the JTextArea. Log file is cp037 character coded. I was reading each file as a byte stream or byte array from the log file & displaying it. Anyways, i managed to display the text properly in JTextArea by cp037 character coding.

Now, User may select a set of characters in the JTextArea. All i want is the position of first character of the user's selected text, from a nearest special character '+'(its character code in cp037 is 4E), which is prior to the selected text. This character may occur at several places in the JTextArea.

In simple sentence, i want the first character location(of user selected text) from nearset '+' which should be occuring prior to the user's selected text.

PS: cp037 is a type of character encoding scheme which is created by IBM & used for IBM Mainframes.

Please fell free to ask me if the question is not clear...:->

+2  A: 

The two methods getSelectionEnd(), getSelectionStart() of JTextComponent will help you.

String firstSelectedChar;
String text = textArea.getText();
int selectionStart = textArea.getSelectionStart();
firstSelectedChar = text.substring(selectionStart, selectionStart + 1);

That may be similar to what you need.

jjnguy
+2  A: 

JTextComponent has a method

public int getSelectionStart()

Returns the selected text's start position. Return 0 for an empty document, or the value of dot if no selection.

public String getSelectedText()

Returns the selected text contained in this TextComponent. If the selection is null or the document empty, returns null.

stacker