identify line in a jtextpane when the row number is entered - java

public static void setJTextPaneFont(JTextPane jtp, Color c, int start_index,int end_index) {
MutableAttributeSet attrs = jtp.getInputAttributes();
StyleConstants.setForeground(attrs, c);
StyledDocument doc = jtp.getStyledDocument();
doc.setCharacterAttributes(start_index, end_index, attrs, false);
}
i created above code to change the forground of of specific word when i enter the start ndex and end index.But now i need to change the the forground when i pass the row number,start_index, and end index.Can you help me with this.How i identify a specific line when i enter the row number.
public void gotoStartOfLine(JTextComponent component, int line) {
Element root = component.getDocument().getDefaultRootElement();
line = Math.max(line, 1);
line = Math.min(line, root.getElementCount());
component.setCaretPosition(root.getElement(line - 1).getStartOffset());
}
i tried above code to go to specific row.but it didint work

How i identify a specific line when i enter the row number.
I think you mean you want the offset of the text for the given row. If so then take a look at the gotoStartOfLine() method from Text Utilities.
That is the code that sets the caret position will give you the starting offset of the line. Then you just add the start/end values to get the offsets of the text to highlight.

Look at using the javax.swing.text.Utilities class, especially the getRowStart(...) and getRowEnd(...) methods.

Related

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 find out line numbers of selected text?

Assume this very small program:
1. package ex1;
2. public interface Resizable {
3. void resize();
4. }
In my editor, if I select line 2-3 using mouse and say click on a button, I want to highlight these texts and also print, which line numbers were selected exactly for the button.
I can do the highlighting part, but I don't know how to find the line numbers of highlighted texts, As I think, I should use a listener, which will detect any changes in editor.
I think I should use an action listener, which will detect when the button is pressed after selecting text blocks. But how I will know, which lines are selected exactly?
The start and end of the highlight can be taken from the caret position dot and mark respectively. These are offsets in the Document. You must then calculate the number of newlines from the start of the document until the mark/do
textArea.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
int startLine = getLine(e.getDot());
int endLine = getLine(e.getMark());
...
}
});
private int getLine(int offset) {
String text = textArea.getDocument().getText(0, offset);
int linenr = 0;
int idx = text.indexOf("\n");
while (idx != -1) {
linenr++;
idx = text.indexOf("\n", idx);
}
return linenr;
}

JTable-Paint the content(text) in a cell

I have a JTable and i have a method which implements search in table rows and columns, i use regular expressions and i want to paint(eg yellow) the text which matches with the regular expression in the cell. I want to paint the text not the background of the cell and only the part of word which matches with reg expression.
The code for my search method is:
for (int row = 0; row <= table.getRowCount() - 1; row++) {
for (int col = 0; col <= table.getColumnCount() - 1; col++) {
Pattern p = Pattern.compile("(?i)" + search_txt.getText().trim());
Matcher m = p.matcher(table.getValueAt(row, col).toString().trim());
if (m.find()){
isFound = true;
table.scrollRectToVisible(table.getCellRect(row, 0, true));
table.setRowSelectionInterval(row, row);
break;
}
}
}
You will need a custom renderer to do this.
The default renderer is a JLabel. So the only way to do this would to wrap HTML around your text string and change the font color of the text you are searching for. You would need to pass the search text to the renderer so the renderer can determine which text to highlight.
The code you posted has a problem in that it will always scroll to the bottom of the table. So what is your exact requirement. Do you want to highlight all cells at one time. Or do you just want to have a "Next" button that will find the next cell with the text. In the first case you would not want to automatically scroll the table. In the second case you would scroll the table.
Also, depending on the requirement you would need to either repaint the entire table (if you show all occurrences at once) or only the current row (if you have next functionality).
Edit:
Normally when you add text to a label you use:
label.setText("user1005633");
If you want to highlight any text containing "100" then you would need to do:
label.setText("<html>user<font color="yellow">100</font>5633</html>");
This is what I mean by wrapping.

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();

Using itext for printing at absolute positions

What is the recommended way of printing a text document as a pdf using absolute positioning ?
I am having a table that I have to print. I am also having the data type lengths and starting positions of the columns.
Since the existing table was a character based, there was no problem in its positioning. But even after using a monotype font (Courier, 10) I am not able to properly position the data and last column(s) of each row erroneously skip to the next line.
In order to present my data as close as the character one, I divided the page into different columns(based on its page size) and then add the contents at the desired place. I am adding chunks of data into the paragraph.
paragraph.add(new Chunk(new VerticalPositionMark(), columnNo*ptUnit, false));
I have tried to tweak the page size, font size and margin lengths, but the data is not properly displayed. Have you encountered any such problems ? please do share your thoughts.
Have you tried ColumnText
When i want to write a paragraph and I do know the amount of lines...I do a cycle incrementing (even it says incrementing and is minus is because the pdf is from "south" to "north" (0 - height) the y in a proportion of the fontsize, something like this
//_valueArray is my string[]
//fontSize is the value of the Size of the font...
//1.5 it's just a magic number :) that give me the space line that i need
//cbLocal is the PdfContentByte of the pdf
for (i = 0; i < _valueArray.Length; i++)
{
var p = new Phrase(_valueArray[i], font);
ColumnText.ShowTextAligned(cbLocal, align, p, x, y, 0);
if (i + 1 != _valueArray.Length)
{
y = y - (fontSize*1.5f);
}
}

Categories