How to change the text of selected text in Java? - java

I want to change the text of selected text in JTextArea.
For example when i press button i want the selected text to be change (Original Text Selected - I want to replace like this when i press the button : Replace:Original Text Selected) this is what i am trying to do in my code,
String replacement = "Replace:" + messageBodyText.getSelectedText() ";
but i have no idea how to change only selected text i am trying to do something but i am changing entire text of JTextArea Hope you understood my question ?
Thanks to Hovercraft Full Of Eels he solved my problem this is my code for other people who are facing the same problem :
int start = messageBodyText.getSelectionStart();
int end = messageBodyText.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(messageBodyText.getText());
strBuilder.replace(start, end, "Replace:" + messageBodyText.getSelectedText() + ".");
messageBodyText.setText(strBuilder.toString());

textComponent.replaceSelection(newText);

JTextComponent (and thus JTextArea) has getSelectionStart() and getSelectionEnd() methods that will help you. Get your text from the JTextArea or its Document, and using these int values you can change your text and replace it into the text component.
For example,
int start = myTextField.getSelectionStart();
int end = myTextField.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(myTextField.getText());
strBuilder.replace(start, end, newText);
myTextField.setText(strBuilder.toString());

Related

How to create highlight textview like Adobe Reader or Medium?

guys.
I need a little bit inspiration right here. I want to create an application that have a highlight feature, just like screenshot below. But, I don't have an idea how to do this. I think Spannable TextView only can't just help me. Do you have some idea?
Thank you.
Example of highlight menu in Medium App
You can use SpannableString
To highlight specific text use this method.
private void highlightString(String input) {
//Get the text from text view and create a spannable string
SpannableString spannableString = new SpannableString(mTextView.getText());
//Get the previous spans and remove them
BackgroundColorSpan[] backgroundSpans = spannableString.getSpans(0, spannableString.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span: backgroundSpans) {
spannableString.removeSpan(span);
}
//Search for all occurrences of the keyword in the string
int indexOfKeyword = spannableString.toString().indexOf(input);
while (indexOfKeyword > 0) {
//Create a background color span on the keyword
spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), indexOfKeyword, indexOfKeyword + input.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//Get the next index of the keyword
indexOfKeyword = spannableString.toString().indexOf(input, indexOfKeyword + input.length());
}
//Set the final text on TextView
mTextView.setText(spannableString);}

How Can I Retrieve a Word From JTextArea From a Right Click?

I would like the user to be able to store text depending on the which word is clicked in the text area.
A right click doesn't change the caret position so the getCaretPosition() method will only work if the caret is positioned on the word your want to select.
For a more general approach you might use the following in your MouseListener:
int offset = textArea.viewToModel( event.getPoint() );
int start = Utilities.getWordStart(textArea, offset);
int end = Utilities.getWordEnd(textArea, offset);
String text = textArea.getText(start, end - start);
JTextComponent.getCaretPosition is what you are looking for; and work from there on to find the word.
Or maybe getSelectedText, if you require the word to be selected by double click.

How to make a textarea filled with text (label) every time the button pressed?

I'm trying to make a text area record that every time the button is press, it means that it has been recorded and should be showing record1, record2, record3, etc. on it.
My goal is that, every button is pressed it will add text to the text area with different text label so that no redundancy.
I tried it with my own with this:
private void btnReqstRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JLabel labelthis = new JLabel("record1");
label.setSize(label.getPreferredSize());
TextArea1.add(label);
TextArea1.revalidate();
TextArea1.repaint();
}
I know it is wrong, but is it possible?
text area is like a mini text editor - you add text to it not other components. Instead of adding labels - just add the text. Something like:
TextArea1.setText(TextArea1.getText() + "record1")
This should append record1 to the existing text in the text area.
According to my experience this is possible.
`private void btnReqstRefreshActionPerformed(java.awt.event.ActionEvent evt) {
i++;//i class level variable(static) to avoid redundancy
//labelThis initialized earlier should be accessible here
String oldText = labelThis.getText().toString();
oldText += "record "+i;
labelThis.setSize(labelThis.getPreferredSize());
TextArea1.add(labelThis);
TextArea1.revalidate();
TextArea1.repaint();
}`

How to get cursor position or location from RichTextArea in GWT?

I want to get cursor position or the location from RichTextArea.
I do not know how to get current cursor position Without any mouse event.
e.g. TextArea has method getCursorPos(), but RichTextArea does not have method like TextArea.
Anyone have any idea?
Thanks in advance...
If you you want to insert something in the RichTextArea at the cursor position, you can do it with the formatter:
RichTextArea.Formatter formatter = richText.getFormatter();
formatter.insertHTML("My text is inserted at the cursor position");
To find a cursor position using JavaScript, try the solution proposed by Tim Down:
Get a range's start and end offset's relative to its parent container
In Vaadin 7.5 #AndreiVolgin answer seems not working. But if somebody wants only to paste some text in cursor position, then CKEditor wrapper for Vaadin add-on may help (link).
Here is an example for posterity:
CKEditorTextField textArea;
// and for example in some listener function we could call:
textArea.insertHtml("<b>some html</b>");
textArea.insertText("sample text");
Don't know if this is still required, but I have been trying to do exactly the same today and could not really find a definitive answer. I did find this non-GWT solution (Get caret (cursor) position in contentEditable area containing HTML content), which needed tweaking everso slightly. Hope this helps someone.
public static native int getCursor(Element elem) /*-{
var node = elem.contentWindow.document.body
var range = elem.contentWindow.getSelection().getRangeAt(0);
var treeWalker = $doc.createTreeWalker(node, NodeFilter.SHOW_TEXT, function(node) {
var nodeRange = $doc.createRange();
nodeRange.selectNodeContents(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
}, false);
var charCount = 0;
while (treeWalker.nextNode()) {
charCount += treeWalker.currentNode.length;
}
if (range.startContainer.nodeType == 3) {
charCount += range.startOffset;
}
return charCount;
}-*/;
Try this out, worked for me. basically you insert a unique text in the rich text area, then you get the index of the inserted text then you remove it.
richText=new RichTextArea();
basicFormatter=richText.getFormatter();
basicFormatter.insertHTML("dummydata");
int cursor=richText.getText().indexOf("dummydata");
basicFormatter.undo();

How to turn off word wrap in JEditorPane?

My JEditorPane automatically wraps words; I don't want that. All I want is a horizontal bar to appear that allows the user to write as much as desired. How can I do that? I have tried several methods. I have overridden the getScrollableTracksViewportWidth(), but that didn't help. Does any one know how I can turn off the word wrap?
A quick google search lead me to this page, which implements it by subclassing the text pane and overriding the getScrollableTracksViewportWidth() method:
// Override getScrollableTracksViewportWidth
// to preserve the full width of the text
public boolean getScrollableTracksViewportWidth() {
Component parent = getParent();
ComponentUI ui = getUI();
return parent != null ? (ui.getPreferredSize(this).width <= parent
.getSize().width) : true;
}
Try this
http://java-sl.com/wrap.html
If you can control the text which is going into, and you are using features of JEditorPane, you can mark the code via html, and use white-space:nowrap; stile property.
jEditorPane1.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<div style='");
if (!wordWrap.isSelected()) { //some checkbox
sb.append("white-space:nowrap;");
}
sb.append("font-family:\"Monospaced\">'");
sb.append("your very interesting long and full of spaces text");
/*be aware, more then one space in row will be replaced by single space
to avoid it you need to substitute by .
Also rememberer that \n have to be repalced by <br>
so filering like:
line = line.replaceAll("\n", "<br>\n"); //be aware, <br/> do not work
line = line.replaceAll(" ", " ");
line = line.replaceAll("\t", " ");
may be usefull.*/
sb.append("</div>");
jEditorPane1.settext(sb.toString()); //jeditor pane do not support addition/insertion of text in html mode
why don't you use a jTextField?
it's only one line.

Categories