I develop some project, it works for tagging a words when i drag the words and click special button.
I want to make tags surrounding a word (begin & end tags with red color) (please refer exam picture, this)
but when it tagged at begin & end of text, it take null-spaces (like picture 2nd).
when I drag that spaces, there's no real space(white space or " " or "\nbsp" - no, never), that's just null space!
I can't select that space!
Pic. Link here
here's my code below:
attribute:
static final Color TAG_COLOR = new Color(255, 50, 50);
static final Color PLAIN_TXT_COLOR = new Color(0, 0, 0);
public static SimpleAttributeSet plainAttr = new SimpleAttributeSet();
public static SimpleAttributeSet tagAttr = new SimpleAttributeSet();
StyleConstants.setAlignment(plainAttr, StyleConstants.ALIGN_JUSTIFIED);
StyleConstants.setForeground(plainAttr, PLAIN_TXT_COLOR);
StyleConstants.setFontSize(plainAttr, 11);
StyleConstants.setBold(plainAttr, false);
StyleConstants.setAlignment(tagAttr, StyleConstants.ALIGN_JUSTIFIED);
StyleConstants.setForeground(tagAttr, TAG_COLOR);
StyleConstants.setFontSize(tagAttr, 11);
StyleConstants.setBold(tagAttr, true);
tagging function:
public static void tag_functiont() {
String taggedName = "tagMark";
int start_sel = mainEditText.getSelectionStart();
int end_sel = mainEditText.getSelectionEnd();
String selected = mainEditText.getSelectedText();
StyledDocument doc = mainEditText.getStyledDocument();
if(selected == null || selected.isEmpty()) return;
try {
String bTag = "__B:"+taggedName+"__";
String eTag = "__E:"+ taggedName +"__";
doc.insertString(start_sel, bTag, tagAttr);
doc.insertString(start_sel+bTag.length()+selected.length(), eTag, tagAttr);
} catch (Exception e) {
e.printStackTrace();
}
}
I also worked all possibility of attributes options.
(some kinds of fonts, all kinds of arrangement;center, right, left, justified )
could someone gimme a piece of advice???
Solved
I added " textPane.setContentType("html/text"); in main source, so foolish.
it triggered <p> & <div> tags.. so the paragraph are gone bad.
Related
I am using itextpdf 7 (7.2.0) to create a pdf file. However even though the TOC part is rendered very well, in the content part the text overflows. Here is my code that generates the pdf:
public class Main {
public static void main(String[] args) throws IOException {
PdfWriter writer = new PdfWriter("fiftyfourthPdf.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf, PageSize.A4,false);
//document.setMargins(30,10,36,10);
// Create a PdfFont
PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN,"Cp1254");
document
.setTextAlignment(TextAlignment.JUSTIFIED)
.setFont(font)
.setFontSize(11);
PdfOutline outline = null;
java.util.List<AbstractMap.SimpleEntry<String, AbstractMap.SimpleEntry<String, Integer>>> toc = new ArrayList<>();
for(int i=0;i<5000;i++){
String line = "This is paragraph " + String.valueOf(i+1)+ " ";
line = line.concat(line).concat(line).concat(line).concat(line).concat(line);
Paragraph p = new Paragraph(line);
p.setKeepTogether(true);
document.add(p.setFont(font).setFontSize(10).setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT));
//PROCESS FOR TOC
String name = "para " + String.valueOf(i+1);
outline = createOutline(outline,pdf,line ,name );
AbstractMap.SimpleEntry<String, Integer> titlePage = new AbstractMap.SimpleEntry(line, pdf.getNumberOfPages());
p
.setFont(font)
.setFontSize(12)
//.setKeepWithNext(true)
.setDestination(name)
// Add the current page number to the table of contents list
.setNextRenderer(new UpdatePageRenderer(p));
toc.add(new AbstractMap.SimpleEntry(name, titlePage));
}
int contentPageNumber = pdf.getNumberOfPages();
for (int i = 1; i <= contentPageNumber; i++) {
// Write aligned text to the specified by parameters point
document.showTextAligned(new Paragraph(String.format("Sayfa %s / %s", i, contentPageNumber)).setFontSize(10),
559, 26, i, TextAlignment.RIGHT, VerticalAlignment.MIDDLE, 0);
}
//BEGINNING OF TOC
document.add(new AreaBreak());
Paragraph p = new Paragraph("Table of Contents")
.setFont(font)
.setDestination("toc");
document.add(p);
java.util.List<TabStop> tabStops = new ArrayList<>();
tabStops.add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
for (AbstractMap.SimpleEntry<String, AbstractMap.SimpleEntry<String, Integer>> entry : toc) {
AbstractMap.SimpleEntry<String, Integer> text = entry.getValue();
p = new Paragraph()
.addTabStops(tabStops)
.add(text.getKey())
.add(new Tab())
.add(String.valueOf(text.getValue()))
.setAction(PdfAction.createGoTo(entry.getKey()));
document.add(p);
}
// Move the table of contents to the first page
int tocPageNumber = pdf.getNumberOfPages();
for (int i = 1; i <= tocPageNumber; i++) {
// Write aligned text to the specified by parameters point
document.showTextAligned(new Paragraph("\n footer text\n second line\nthird line").setFontColor(ColorConstants.RED).setFontSize(8),
300, 26, i, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 0);
}
document.flush();
for(int z = 0; z< (tocPageNumber - contentPageNumber ); z++){
pdf.movePage(tocPageNumber,1);
pdf.getPage(1).setPageLabel(PageLabelNumberingStyle.UPPERCASE_LETTERS,
null, 1);
}
//pdf.movePage(tocPageNumber, 1);
// Add page labels
/*pdf.getPage(1).setPageLabel(PageLabelNumberingStyle.UPPERCASE_LETTERS,
null, 1);*/
pdf.getPage(tocPageNumber - contentPageNumber + 1).setPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS,
null, 1);
document.close();
}
private static PdfOutline createOutline(PdfOutline outline, PdfDocument pdf, String title, String name) {
if (outline == null) {
outline = pdf.getOutlines(false);
outline = outline.addOutline(title);
outline.addDestination(PdfDestination.makeDestination(new PdfString(name)));
} else {
PdfOutline kid = outline.addOutline(title);
kid.addDestination(PdfDestination.makeDestination(new PdfString(name)));
}
return outline;
}
private static class UpdatePageRenderer extends ParagraphRenderer {
protected AbstractMap.SimpleEntry<String, Integer> entry;
public UpdatePageRenderer(Paragraph modelElement, AbstractMap.SimpleEntry<String, Integer> entry) {
super(modelElement);
this.entry = entry;
}
public UpdatePageRenderer(Paragraph modelElement) {
super(modelElement);
}
#Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutResult result = super.layout(layoutContext);
//entry.setValue(layoutContext.getArea().getPageNumber());
if (result.getStatus() != LayoutResult.FULL) {
if (null != result.getOverflowRenderer()) {
result.getOverflowRenderer().setProperty(
Property.LEADING,
result.getOverflowRenderer().getModelElement().getDefaultProperty(Property.LEADING));
} else {
// if overflow renderer is null, that could mean that the whole renderer will overflow
setProperty(
Property.LEADING,
result.getOverflowRenderer().getModelElement().getDefaultProperty(Property.LEADING));
}
}
return result;
}
#Override
// If not overriden, the default renderer will be used for the overflown part of the corresponding paragraph
public IRenderer getNextRenderer() {
return new UpdatePageRenderer((Paragraph) this.getModelElement());
}
}
}
Here are the screen shots of TOC part and content part :
TOC :
Content :
What am I missing? Thank you all for your help.
UPDATE
When I add the line below it renders with no overflow but the page margins of TOC and content part differ (the TOC margin is way more than the content margin). See the picture attached please :
document.setMargins(30,60,36,20);
Right Margin difference between TOC and content:
UPDATE 2 :
When I comment the line
document.setMargins(30,60,36,20);
and set the font size on line :
document.add(p.setFont(font).setFontSize(10).setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT));
to 12 then it renders fine. What difference should possibly the font size cause for the page content and margins? Are not there standard page margins and page setups? Am I unknowingly (I am newbie to itextpdf) messing some standard implementations?
TL; DR: either remove setFontSize in
p
.setFont(font)
.setFontSize(12)
//.setKeepWithNext(true)
.setDestination(name)
or change setFontSize(10) -> setFontSize(12) in
document.add(p.setFont(font).setFontSize(10).setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT));
Explanation: You are setting the Document to not immediately flush elements added to that document with the following line:
Document document = new Document(pdf, PageSize.A4,false);
Then you add an paragraph element with font size equal to 10 to the document with the following line:
document.add(p.setFont(font).setFontSize(10).setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.LEFT));
What happens is that the element is being laid out (split in lines etc), but now drawn on the page. Then you do .setFontSize(12) and this new font size is applied for draw only, so iText calculated that X characters would fit into one line assuming the font size is 10 while in reality the font size is 12 and obviously fewer characters can fit into one line.
There is no sense in setting the font size two times to different values - just pick one value you want to see in the resultant document and set it once.
It's thought that the solution has been defined already. I'd like to think so but unfortunately the results are the same trying yet a 3rd solution produced no change to the text color...
..
I'm trying to change the color of a certain word in a JTextPane (to red) to
show it's status. There are a number of examples and I've tried several but the end result is either the text remains unchanged or the entire text's color changes.
I will place a snippet of code here because the class is rather large
..
textPane = new JTextPane();
textPane.setFont(new Font("Arial", Font.PLAIN, 12));
..
String productName = "PC";
String vendorName = "DELL";
String statusOfProd = "OFF";
String theObject = "Product " + productName + " Vendor " + vendorName;
String taData = theObject + "\n";
textPane.setText(taData);
if (statusOfProd.equals("OFF")){
addColor2Pane(productName, Color.RED);
}
..
private void addColor2Pane(String value2Change, Color color2Use) {
String theData = textPane.getText();
int v2cIndex = theData.indexOf(value2Change);
int v2cLen = value2Change.length();
try {
textPane.getHighlighter().addHighlight(v2cIndex, v2cIndex + v2cLen,
new DefaultHighlighter.DefaultHighlightPainter(color2Use));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
..
// Attributes
protected JTextPane textPane;
public static String taData;
The result of the above method has no effect. If I change the "addColor2Pane"
method to below the result renders all text in the pane RED which is not what I'm trying to achieve.
..
private void addColor2Pane(String value2Change, Color color2Use) {
StyleContext sc = StyleContext.getDefaultSytleContext();
AttributeSet aSet = sc.addAttribute(sc.getEmptySet(),
StyleConstants.Foreground,
color2Use);
aSet = sc.addAttribute(aSet,
StyleConstants.FontFamily,
"Lucida Console");
aSet = sc.addAttribute(aSet,
StyleConstants.Alignment,
StyleConstants.ALIGN_LEFT);
int v2cInd = theData.indexOf(value2Change);
int v2cLen = value2Change.length();
textPane.setCaretPosition(v2cInd);
textPane.setCharacterAttributes(aSet, true);
textPane.replaceSection(value2Change);
}
The desired result is ONLY have the color of the productName set to RED. Suggestions?
Creating 2 PdfSignatureFormFields the same way, i got 2 fields differently displayed in Adobe Reader : one with a little picture indicating a signature field and the other with no indication.
I use a Cell setNextRenderer call to create these fields as showed in the next extract :
static private Cell createSignatureFieldCell(PdfDocument document, String name, String label, PdfFont font) {
Cell cell = new Cell();
cell.setHeight(100);
cell.setNextRenderer(new SignatureCellEvent(cell,name,label));
return cell;
}
static private class SignatureCellEvent extends CellRenderer
{
protected String fieldname;
protected String labelcontent;
public SignatureCellEvent(Cell modelElement, String fieldname,String label) {
super(modelElement);
this.fieldname=fieldname;
this.labelcontent=label;
}
#Override
public void draw(DrawContext drawContext)
{
float x = getOccupiedAreaBBox().getLeft() ;
float y = (getOccupiedAreaBBox().getTop() + getOccupiedAreaBBox().getBottom()) / 2;
PdfDocument doc=drawContext.getDocument();
PdfAcroForm form=PdfAcroForm.getAcroForm(doc, true);
Rectangle rect = new Rectangle(x, y - 10, 50, 50);
PdfSignatureFormField field = PdfFormField.createSignature(doc,rect);
field.setFieldName(fieldname);
field.setRequired(true);
form.addField(field);
}
}
Sorry for the inconvenience caused !
I've found the reason of this behaviour:
It occurs when there is a field name collision in the document.
In my case, a dynamically created field had the same name as a preexisting static field.
Regards,
David L.
TL;DR
How do you create a PDF from a JSON object that contains a String written in HTML.
Example JSON:
{
dimensions: {
height: 297,
width: 210
},
boxes: [
{
dimensions: {
height: 10,
width: 190
},
position: {
x: 10,
y: 10
},
content: "<h1>Hello StackOverflow</h1>, I think you are <strong></strong>! I hope someone can answer this!"
}
]
}
Tech used in front-end: AngularJS 1.4.9, ui.tinymce, ment.io
Back-end: whatever works.
I want to be able to create templates for PDFs. The user writes some text in a textarea, uses some variable that will later be replaced with actual data, and when the user presses a button, a PDF should be returned with the finished product.
This should be very generic. So it would be able to be used in pretty much anything.
So, minimal example: The user writes a little text in TinyMCE like
<h1>Hello #[COMMUNITY]</h1>, I think you are <strong>great</strong>! I hope someone can answer this!
This text contains two variables that the user gets with the help of the ment.io plugin. The actual variables is supplied from the controller.
This text is written in an AngularJS version of TinyMCE which also has Ment.io on it which supplies a nice view of available variables.
When the user presses the Save button, a JSON object like the following is created, which is the template.
{
dimensions: {
height: 297,
width: 210
},
boxes: [
{
dimensions: {
height: 10,
width: 190
},
position: {
x: 10,
y: 10
},
content: "user input"
}
]
}
I have a directive in Angular that can generate any number of boxes really, in any size (generic-ho!). This part works great. Simply send in how big you want the 'page' (in mm, so the example says A4-paper size) in the first dimensions object as you see in the object. Then in the boxes you define how big they should be, and where on the 'paper' it should go. And then finally the content, which the user writes in a TinyMCE textarea.
Next step: The back-end replaces the variables with actual data. Then pass it on to the generator.
Then we come to the tricky part: The actual generator. This should accept, preferably, JSON. The reason for this is because any project should be able to use it. The front-end and the PDF-generator goes hand in hand. They don't care what's in the middle. This means that the generator can be written in pretty much anything. I'm a Java-developer though, so Java is preferable (hence the Java-tag).
Solutions I've found are:
PDFbox, but the problem with using that is the content that TinyMCE produces. TinyMCE outputs HTML or XML. PDFBox does not handle this, at all. Which means I have to write my own HTML or XML parser to try and figure out where the user wants bold-text, and where she wants italics, headings, other font, etc. etc. And I really don't want that. I've been burned on that before. It is on the other hand great for placing the text in the correct places. Even if it is the raw text.
I've read that iText does HTML. But the the AGPL-license pretty much kills it.
I've also looked at Flying Saucer that takes XHTML and creates a PDF. But it seems to rely on iText.
The solution I'm looking at now is a convoluted way to use Apache FOP. FOP takes an XSL-FO object to work on. So the trouble here is to actually dynamically create that XSL-FO object. I've also read that the XSL-FO standard has been dropped, so unsure how future-proof this approach will be. I've never worked with neither FOP nor XSLT. So the task seems daunting.
What I'm currently looking at is taking in the output from TinyMCE, run that through something like JTidy to get XHTML. From the XHTML create a XSLT file (in some magical way). Create a XSL-FO object from the XHTML and XSLT. And the generate the PDF from the XSL-FO file. Please tell me there is an easier way.
I can't have been the first to want to do something like this. Yet searching for answers seems to yield very few actual results.
So my question is basically this: How do you create a PDF from a JSON-object like the above, which contains HTML, and get the resulting text to look like it does when you write it in TinyMCE?
Have in mind that the object can contain an unlimited number of boxes.
So. After some research and work I decided to actually go with PDFbox for the generation. I've also been very strict about what I accept as content input. Right now, I really just accept bold, italics and headings. So I look for <strong>, <em>, and <h[1-6]> tags.
To begin with, I updated my input JSON a bit, more wrapping really.
{
[
documents: [
{
pages: [
{
dimensions: {width: 210, height, 297},
boxes: [
dimensions: {width: 190, height: 40},
placement: {x: 10, y, 10},
content: "Hello <strong>StackOverflow</strong>!"
]
}
]
}
]
]
}
And the reason is because I want to be able to put out lots and lots of documents in the same PDF. Think if you are doing a mass send out of letters. Each document is slightly different, but you still want it all in the same PDF. You could of course do this all with just the pages level, but if one document is several pages, it's nicer to have the separated, I think.
My actual code is about 500 lines long, so I won't paste it all here, just the basic parts to be of help, and that' still around 150 lines.
Here goes:
public class Generator {
public static ByteArrayOutputStream generatePDF(final Bundle bundle) {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
pdf = new PDDocument();
for (final Document document : bundle.documents) {
for (final Page page : document.pages) {
pdf.addPage(generatePage(pdf, page));
}
}
pdf.save(output);
pdf.close();
return output;
}
private static generatePage(final PDDocument document, final Page page) {
final PDRectangle rect = new PDRectangle(mmToPoints(page.dimensions.width)mmToPoints(page.deminsions.height));
final PDPage pdPage = new PDPage(rect);
final PDPageContentStream cs = new PDPageContentStream(document, pdPage);
for (final Box box : page.boxes) {
resetFont(cs); // Reset the font when starting new box so missing ending tags don't mess up the next box.
final String pc = processContent(box.content); // Make the content prettier. Eg. strip all <p>, replace </p> with \n, strip all <div> tags, etc.
lines(Arrays.asList(processContent.split("\n")), box, cs);
}
cs.close();
return pdPage;
}
private static float mmToPoints(final float mm) {
// 1 inch == 72 points (standard DPI), 1 inch == 25.4mm. So, mm to points means (mm / inchInmm) * pointsInInch
return (float) ((mm / 25.5) * 72);
}
private static lines(final List<String> lines, final Box box, final PDPageContentStream cs) {
if (lines.size() == 0) { return; }
cs.beginText();
cs.moveTextPositionByAmount(mmToPoints(box.placement.x), mmToPoints(box.placement.y));
// Now we begin the tricky part
for (int i = 0, length = lines.size; i < length; ++i) {
final String line = lines.get(i);
final List<Word> wordList = new ArrayList<>();
final String[] splitArray = line.split(" ");
final float fontHeight = fontHeight(currentFont(), currentFontSize()); // Documented elsewhere
cs.appendRawCommands(fontHeight + " TL\n");
if (i == 0) { addNewLine(cs); } // PDFbox starts at the bottom, we start at the top. Add new line so we are inside the box
for (final String index : splitArray) {
final String word = index + " "; // We removed spaces when we split on them, add it to words now.
final StringBuilder wordBuilder = new StringBuilder();
boolean addWord = true;
for (int j = 0; wordLength = word.length(); j < wordLength ; ++j){
final char c = word.charAt(j);
if (c == '<') { // check for <strong> and those
final StringBuilder command = new StringBuilder();
if (addWord && wordBuilder.length() > 0) {
wordList.add(new Word(wordBuilder.toString(), currentFont(), currentFontSize()));
wordBuilder.setLength(0);
addWord = false;
}
for (; j < wordLength; ++j) {
final char c1 = word.charAt(j);
command.append(c1);
if (c1 == '>') {
if (j + 1 < wordLength) { addWord = true; }
break;
}
}
final boolean b = parseForFontChange(command.toString());
if (!b) { // If it wasn't a command, we want to append it to out text
wordBuilder.append(command.toString());
}
} else if (c == '&') { // check for html escaped entities
final int longestHTMLEntityName = 24 + 2; // &ClocwiseContourIntegral;
final StringBuilder escapedChar = new StringBuilder();
escapedChar.append(c);
int k = 1;
for (; k < longestHTMLEntityName && j + k < wordLength; ++k) {
final char c1 = word.charAt(j + k);
if (c1 == '<' || c1 == '>') { break; } // Can't be an espaced char.
escapedChar.append(c1);
if (c1 == ';') { break; } // End of char
}
if (escapedChar.indexOf(";") < 0) { k--; }
wordBuilder.append(StringEspaceUtils.unescapedHtml4(escapedChar.toString()));
j += k;
} else {
wordBuilder.append(c);
}
}
if (addWord) {
wordList.append(new Word(wordBuilder.toString(), currentFont(), currentFontSize()));
}
}
writeWords(wordList, box, cs);
if (i < length - 1) { addNewLine(cs); }
}
cs.endText();
}
public static void writeWords(final List<Word> words, final Box box, final PDPageContentStream cs) {
final float boxWidth = mmToPoints(box.dimensions.width);
float lineWidth = 0;
for (final Word word : words) {
lineWidth += word.width;
if (lineWidth > boxWidth) {
addNewLine(cs);
lineWidth = word.width;
}
if (lineWidth > boxWidth) { // Word longer than box width
lineWidth = 0;
final String string = word.string;
for (int i = 0, length = string.length(); i < length; ++i) {
final char c = string.charAt(i);
final float charWidth = calculateStringWidth(String.valueOf(c), word.font, word.fontSize);
lineWidth += charWidth;
if (lineWidth > boxWidth) {
addNewLine(cs);
lineWidth = charwidth);
}
drawChar(c, word.font, word.fontSize, cs);
}
} else {
draWord(word, cs);
}
}
}
}
public class Word {
public final String string;
public final PDFont font;
public final float fontSize;
public final float width;
public final float height;
public Word(final String string, final PDFont font, final float fontSize) {
this.string = string;
this.font = font;
this.fontSize = fontSize;
this.width = calculateStringWidth(string, font, fontSize);
this.height = calculateStringHeight(string, font, fontSize);
}
}
I hope this helps someone else facing the same problem. The reason to have a Word class is if you want to split on words, rather than chars.
Lots of other posts describe how to use some of these helper methods, like calculateStringWidth etc. So They are not here.
Check How to Insert a Linefeed with PDFBox drawString for newlines and fontHeight.
How to generate multiple lines in PDF using Apache pdfbox for string width.
In my case the parseForFontChange method changes the current font and font size. What's active is of course returned by the method currentFont() and currentFontSize. I use regexes like (?ui:(<strong>)) to check if a bold-tag was in there. Use what suits you.
I am building a custom a find and replace in java. I browse a text file and load the contents in a textarea. Now I have a textBox, where I input a text that needs to be searched.
What is the best way to search the text. I know a way using string.indexOf(), but I also need highlighting. So please help me out.
First of all read Text and New Lines for information on how to get the text to search.
Then to highlight the text your find you need to use a Highlighter. The code is something like:
Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
int offset = text.indexOf(searchWord);
int length = searchWord.length();
while ( offset != -1)
{
try
{
textPane.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(searchWord, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
indexOf is the easiest way, but might not be the fastest way.
Why isn't indexOf working for you? You will get the index of the match, and you know the length of the match, so just highlight the text that matched.
I am having the same problem with my text editor. I didn't use a highlighter though, I used
textArea.select(int i1, int i2); //where i1 is where your selection begins and i2 is where it ends.
also an easy way to find and replace is:
textArea.setText(textArea.getText().replaceAll(String string1, String string2));
final String inputValue = JOptionPane.showInputDialog("Find What?");
final int l1 = jTextArea1.getText().indexOf(inputValue);
final int l2 = inputValue.length();
if (l1 == -1) {
JOptionPane.showMessageDialog(null, "Search Value Not Found");
} else {
jTextArea1.select(l1, l2+l1);
}
if (e.getSource() == btnSearch && !searchWord.getText().isEmpty()) {
Highlighter.HighlightPainter painter =
new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
templateArea.getHighlighter().removeAllHighlights();
int offset = templateArea.getText().indexOf(searchWord.getText());
int length = searchWord.getText().length();
while ( offset != -1)
{
try
{
templateArea.getHighlighter().addHighlight(offset, offset + length, painter);
offset = templateArea.getText().indexOf(searchWord.getText(), offset+1);
}
catch(BadLocationException exception) { System.out.println(exception); }
}
}
}