JTextPane and highlighting

Hello!
Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
     private DefaultStyledDocument doc = new DefaultStyledDocument();
     private JTextPane txtTest = new JTextPane(doc);
     private Random random = new Random();
     private void appendLong() throws BadLocationException {
          String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
          int start = doc.getLength();
          doc.insertString(doc.getLength(), str, null);
          int end = doc.getLength();
          txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
     private Color randomColor() {
          int r = intRand(0, 255);
          int g = intRand(0, 255);
          int b = intRand(0, 255);
          return new Color(r, g, b);
     private int intRand(int low, int hi) {
          return random.nextInt(hi - low + 1) + low;
     }As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
I can fix this problem by changing the insert line to this:
doc.insertString(doc.getLength()+1, str, null);With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
I've tried in veign to hack that newline character away. For example:
          if (doc.getLength() == 0) {
               doc.insertString(doc.getLength(), str, null);
          } else {
               doc.insertString(doc.getLength()+1, str, null);
          } But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
I've also tried:
txtTest.setText(txtTest.getText()+str);That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!

It may work but it is nowhere near the correct
solution.It seems to me the "correct" solution would be for Sun to fix the issue, because it seems they are secretly inserting a newline character into my Document. Here's a compilable program that shows what I mean:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultStyledDocument;
public class TestFrame extends JFrame {
     private JButton btnAppend = new JButton("Append");
     private DefaultStyledDocument doc = new DefaultStyledDocument();
     private JTextPane txtPane = new JTextPane(doc);
     private Random random = new Random();
     public TestFrame() {
          setSize(640, 480);
          setLocationRelativeTo(null);
          addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                    dispose();
          getContentPane().add(new JScrollPane(txtPane), BorderLayout.CENTER);
          getContentPane().add(btnAppend, BorderLayout.SOUTH);
          btnAppend.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    doBtnAppend();
     private void doBtnAppend() {
          try {
               String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
               int start = doc.getLength();
                * This line causes all highlights to have the same color,
                * but the text correctly starts on the first line.
               doc.insertString(doc.getLength(), str, null);
                * This line causes all highlights to have the correct
                * (different) colors, but the text incorrectly starts
                * on the 2nd line.
//               doc.insertString(doc.getLength()+1, str, null);
                * This if/else solution causes the 2nd appended text to
                * incorrectly start on the 2nd line, instead of being
                * concatinated with the existing text on the first line.
                * (a newline character is somehow inserted after the first
                * line)
//               if (doc.getLength() == 0) {
//                    doc.insertString(doc.getLength(), str, null);
//               } else {
//                    doc.insertString(doc.getLength()+1, str, null);
               int end = doc.getLength();
               txtPane.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
          } catch (BadLocationException e) {
               e.printStackTrace();
     public static void main(String[] args) {
          EventQueue.invokeLater(new Runnable() {
               public void run() {
                    new TestFrame().setVisible(true);
     private Color randomColor() { return new Color(intRand(0, 255), intRand(0, 255), intRand(0, 255)); }
     private int intRand(int low, int high) { return random.nextInt(high - low + 1) + low; }
}Try each of the document insert lines in the doBtnAppend method and watch what it does. (comment out the other 2 of course)
It wastes resources and is inefficient. A lot of work
goes on behind the scenes to create and populate a
Document.I tracked the start and end times in a thread loop to benchmark it, and most of the time the difference is 0 ms. When the document gets to about 7000 characters I start seeing delays on the order of 60 ms, but I'm stripping off text from the beginning to limit the max size to 10000. It might be worse on slower computers, but without a "correct" and working solution it's the best I can come up with. =)

Similar Messages

  • JTextPane Line Highlighting

    Hi.
    I have a JTextPane, and I would like to make it highlight a whole row, or line, that the cursor is on.
    I DON'T want to set the selection color. I want the current row that is selected to highlight the background of the text for the whole width of the row, then unhighlight it when it is deselected.
    Please help.
    Thanks!

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

  • Normally when I go to a website the site automatically opens, now with the updated Firefox I have to go to the http: line and highlight and turn arrow to red. Why?

    The website shows on the bottom line with other websites visited, but will not open automatically, I have to go up to the mozilla.com toolbar and highlight the website and then go to the arrow and highlight it so that it turns red. Uses a lot of extra time.

    You may have a user agent that is corrupted.
    *http://browserspy.dk/useragent.php
    See also:
    *https://support.mozilla.org/kb/Websites+or+add-ons+incorrectly+report+incompatible+browser

  • Problem with JTextPane and StateInvariantError

    Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags to the beginning and end of any text that is to be bold. When the other client receives the message, the program will take out all of the <b> and </b> tags and display any text between them as bold (or italic with <i> and </i>). I've searched the forums a lot and figured out several ways to make the text bold, and several ways to determine which text is bold before sending the text, but none that work together. Currently, I add the bold tags with this code: (note: messageDoc is a StyledDocument and messageText is a JTextPane)
    public String getMessageText() {
              String text = null;
              boolean bold = false, italic = false;
              for (int i = 0; i < messageDoc.getLength(); i++) {
                   messageText.setCaretPosition(i);
                   if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && !bold) {
                        bold = true;
                        if (text != null) {
                             text = text + "<b>";
                        else {
                             text = "<b>";
                   else if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        // Do nothing
                   else if (!StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        bold = false;
                        if (text != null) {
                             text = text + "</b>";
                        else {
                             text = "</b>";
                   try {
                        if (text != null) {
                             text = text + messageDoc.getText(i,1);
                        else {
                             text = messageDoc.getText(i, 1);
                   catch (BadLocationException e) {
                        System.out.println("An error occurred while getting the text from the message document");
                        e.printStackTrace();
              return text;
         } // end getMessageText()When the message is sent to the other client, the program searches through the received message and changes the text between the bold tags to bold. This seems as if it should work, but as soon as I click on the bold button, I get a StateInvariantError. The code for my button is:
    public void actionPerformed(ActionEvent evt) {
              if (evt.getSource() == bold) {
                   MutableAttributeSet bold = new SimpleAttributeSet();
                   StyleConstants.setBold(bold, true);
                   messageText.getStyledDocument().setCharacterAttributes(messageText.getSelectionStart(), messageText.getSelectionStart() - messageText.getSelectionEnd() - 1, bold, false);
         } //end actionPerformed()Can anyone help me to figure out why this error is being thrown? I have searched for a while to figure out this way of doing what I'm trying to do and I've found out that a StateInvariantError has been reported as a bug in several different circumstances but not in relation to this. Or, if there is a better way to add and check the style of the text that would be great as well. Any help is much appreciated, thanks in advance.

    Swing related questions should be posted in the Swing forum.
    Can't tell from you code what the problem is because I don't know the context of how each method is invoked. But it would seem like you are trying to query the data in the Document while the Document is being updated. Try wrapping the getMessageText() method is a SwingUtilities.invokeLater().
    There is no need to write custom code for a Bold Action you can just use:
    JButton bold = new JButton( new StyledEditorKit.BoldAction() );Also your code to build the text String is not very efficient. You should not be using string concatenation to append text to the string. You should be using a StringBuffer or StringBuilder.

  • I cannot change song order on playlist with highlight and drag. I have turned off shuffle and highlighted the far left column( up/down arrow) of playlist. My mac pro is running 10.5.8  and am using itunes 10.4.

    I cannot change song order on playlists (old or new) with highlight and drag. I have turned off shuffle and highlighted the far left column (up/down arrow) of playlist. My mac pro is running 10.5.8  and am using itunes 10.4. I can't drag and drop "music" to "playlist" but can right click and get the option to "add to playlist." No such option for moving song within playlist, only the up and down arrow which moves song from top to bottom list, so if it is #4 from top it will move to #4 from bottom. Stupid I know. I spent over an hour with Apple support, reinstalled itunes, restarted and rebooted computer. Networked with my laptop which is running 10.6.8 and itunes 10.4 and it can drag and drop. The final Apple support solution was to reinstall my operating system. I would prefer not to. Any other ideas?

    After looking at other people's posts, I think it's official: there is a bug. Itunes support said I should not have lost the drag/drop tool and I haven't on the laptop that is running itunes 10.4 and operating system 10.6.8. I chatted with someboby who lost both his drag/drop and side scroll and what we have in common is a wacom tablet for a mouse. My laptop is a wireless mouse. I reinstalled whatever updated driver that wacom has out there, shut the system down for night, hoping for magic, but alas none to be had. So if I want to change song order, I network the laptop and desktop, share the screen on the laptop, drag and drop to my heart's content and curse Apple for making me work this hard to find the tool that was once at my fingertips. Apple also let me know that if I want to share songs in household that the hundreds on songs that were purchased for .99 need to be repurchased for another .30. Maybe Apple is holding my drag/drop tool captive til I pay up the money or Maybe the next update will fix the problem, I for one give up for now.

  • Email notifications in HUB stop happening.. and highlighting of new emails also stopped

    All of a sudden I am no loner getting notification when new email comes ... either in the HUB view or in my inbox.   Also the new emails used to be highlighted in there and that seems to have stopped also.
    I did not change any settings.
    I also tried removing the battery
    Any ideas?

    Yes very.. it just seem to start happening.. It was notifying and highlighting before today I thought

  • Creating Electronic Binders Using PDF Portfolio - Commenting and Highlighting

    For a few years now I have been using Portfolios to create electronic versions of binders.  Users want to be able to review, search, highlight and comment within the PDFs - and each have a copy with their comments.  Security is also a big deal.  My main question is:  Is using Adobe Portfolios the best solution for making an electronic binder, or does Adobe or another vendor offer a better one?  Recently I saw a product called GDoc Binder that looks promising.  For now using the Portfolios is the best solution I know of.
    Problems with the current solution:  Right now I have to create multiple copies of the document to allow users to comment and highlight on their own copy.  File size can be problematic - if it's too big searching can take a long time even after I index the file.  Updating and adding sections is problematic since if you update a page or file you could lose their comments, and so I have to update multiple copies of the same file.  I know you can export and import comments but that can be complex/time consuming. One question I have: Is there a search and/or report on comments and highlights from the full Portfolio rather than just one at a time?
    Since Adobe Pro X I have had to use a custom template from PracticalPDF.com to recreate the list navigation of Adobe Pro 9. I did see another post saying that the use of Flash with Portfolios mean that it's day are numbered. Question: I am curious if this is true, and if Portfolios using Flash are becoming obsolete, what Adobe Pro would use for an alternative?
    Thank you in advance for any insight and answers - it is greatly appreciated.

    Take a look at the free 'CoolList' layout from Joel Geraci : http://blog.practicalpdf.com/portfolios/

  • How can I resize a pdf page content with annotations and highlights in Acrobat Pro?

    How can I resize a pdf page content with annotations and highlights in Acrobat Pro while maintaining page size and annotation/highlight interactivity? I've tried to use the crop tool in Acrobat Pro (9) and the page does resize, but the highlights and annotations go all over the place. I specifically need to scale the page content smaller (83%) but maintain page size and annotation/highlight to content connection and interactivity.

    An old trick (not recommended) would be to print to a new PDF with the page size selected but a scaling of the content. Only print the document, not the markup, to a new PDF. Close that PDF when done and reopen the old one (or maybe a copy of the old one for safety) and use Document Replace pages and select the new document to replace your current pages. You will then have to go back through the markup to locate it all correctly. There may be a more elegant way, but this may be the fastest.

  • Text find and Highlight

    I have a textbox that I am loading text from instructionsArray that gets data from a XML file.  I want to search that textbox for a word that might be in the dictionaryArray that gets data from and XML file. Then I want the word if its there to be higlighted in red and be able to rollover  or click the word to get a popup that shows the words definition that is also in the dictionaryArray.    SO the code for all of this as I have it so far builds a rectangle backgournd and addes the textbox to it. The MA is a variable that tells what set of instuctions it is on (1, 2, etc).  Everything works except the search and highlight. Is this better?
    XML FILE
    CODE for XML Dictionary
    <?xml version="1.0" encoding="utf-8"?>
    <dictionary>
              <allWords>
                        <word>Enzymes</word>
                        <definition>Natural chemical substances found in all plant and animal tissue. In growing plants, they aid in all growth processes including maturation and ripening. After maturity, continued activity of enzymes can cause undesirable changes in color, flavor and texture. Enzymes that cause these undesirable changes are destroyed during heat processing of foods.</definition>
                        <visualAids>
                                  <image src="Flash_pictures/tn/tn_mouth.png" title="Mouth" url="Flash_pictures/mouth.png" />
                        </visualAids>
              </allWords>
              <allWords>
                        <word>Oxidation</word>
                        <definition>Gain in oxygen or loss of electrons. Acid Foods: Foods containing natural acids, those that had vinegar added to them or those produced by controlled microbial fermentation are classified as acid foods. This food group includes fruits, tomatoes, pickles, sauerkraut and relishes. Because microorganisms do not thrive in acid, these foods can be safely processed in a water bath canner at 212 F (100 C) </definition>
                        <visualAids>
                                  <image src="Flash_pictures/tn/tn_mouth.png" title="Mouth" url="Flash_pictures/mouth.png" />
                        </visualAids>
              </allWords>
    </dictionary>
    CODE FOR XML INSTRUCTIONS
    <?xml version="1.0" encoding="utf-8"?>
    <allInsturctions>
              <actInstructions>
                        <name>
                                  act1
                        </name>
                        <boxtext>
                                  Before tomatoes enter the plant, they must be graded for quality. The quality of the tomatoes on a truckload determines how much the producer gets paid. Only grade A/B tomatoes will be used in canning. Grade C tomatoes may be used for other types of tomato food products such as juice or salsa.
                        </boxtext>
                        <instructions>
                                  <![CDATA[ Tomato Grading
    <p>Enzymes The quality grade of a tomato is based on 3 things: size, ripeness and defects. This step is only an average of the quality for the whole truck so the producer can be fairly paid. Later, every tomato will be graded both by machine and by hand before being processed.
    <p>Minimum quality requirements must be met to continue processing or you risk the final canned product getting recalled by the USDA. The estimated Grade quality for the truck is not sufficient enough. Each tomato is graded for redness by a machine where tomatoes that are too green are siphoned off for juice production. Tomatoes are also evaluated by hand so that any broken fruit can be discarded. Broken fruit will jam up the machinery and not peel properly.</p>
    <p> Now it is your turn to practice grading tomatoes in order to determine how much to pay the producer!
    1.          Take a sample of tomatoes from 3 different spots in the truckload. <br/>2.          Give each separate sample a grade of A/B, or C. <br/>3.          Then average the 3 samples together to determine how much to pay you producer and decide what finished product to use the tomatoes for.
    </p>
    ]]>
                        </instructions>
                        <question>
                                  <![CDATA[<br/> <br/> <br/> How would you grade this truck?</p>]]>
                        </question>
                        <options>
                                  <a>Grade A</a>
                                  <b>Grade B</b>
                                  <c>Grade C</c>
                        </options>
                        <image src="Flash_pictures/tn/tn_mouth.png" title="Mouth" url="Flash_pictures/mouth.png" />
                        <video>
                                  Arrival
                        </video>
              </actInstructions>
    </allInsturctions>
    //LOAD EXTERNAL XML FILES
    function loadXML():void
              XMLLoader.addEventListener(Event.COMPLETE, xmlLoadComplete);
              XMLDataRequest = new URLRequest(XMLFiles[XMLFilesPointer]);
              XMLLoader.load(XMLDataRequest);
              trace(XMLFiles[XMLFilesPointer]);
    function xmlLoadComplete(e:Event):void
              XMLLoader.removeEventListener(Event.COMPLETE, xmlLoadComplete);
              var xmlData = XML(e.target.data);
              //distinguish between both xml types
              xmlData.ignoreWhitespace = true;
              if (xmlData.actInstructions != undefined)
              {//if instructions node exists, then it is instructions xml
                        trace('instructions xml file');
                        for (var b = 0; b < xmlData.actInstructions.length(); b++)
                                  instructionsArray.push({name:xmlData.actInstructions[b].name.text(), boxtext:xmlData.actInstructions[b].boxtext.text(), instructions: xmlData.actInstructions[b].instructions.text(), question: xmlData.actInstructions[b].question.text(), image: xmlData.actInstructions[b].visualAids.text(), video: xmlData.actInstructions[b].video.text() });
              if (xmlData.allWords != undefined)
              {//if movie node exists, then it is dictionary xml
                        trace('dictionary xml file');
                        trace(xmlData.allWords.length());
                        for (var n = 0; n < xmlData.allWords.length(); n++)
                                  dictionaryArray.push({word: xmlData.allWords[n].word.text(), definition: xmlData.allWords[n].definition.text(), image: xmlData.allWords[n].visualAids.text() });
              XMLFilesPointer++;
              if (XMLFilesPointer < XMLFiles.length)
                        loadXML();
    //build display and add text
    var words:Array = instructionsArray[MA].instructions.split(/\s+/);
    var highlight:TextFormat = new TextFormat("Arial",14,0xff0000,null,true);
    var dictionaryTimer:Timer = new Timer(100,dictionaryArray.length-1);
    dictionaryTimer.addEventListener(TimerEvent.TIMER, onTimer);
    dictionaryTimer.start();
    function onTimer(e:TimerEvent):void
              textbox.setTextFormat(textbox.defaultTextFormat);
              var re:RegExp = new RegExp("\\b"+words[dictionaryTimer.currentCount]+"\\b", "gi");
              var result:Object = re.exec(instructionsArray[MA].instructions);
              while (result)
                        textbox.setTextFormat(highlight, result.index, result.index+words[dictionaryTimer.currentCount].length);
                        result = re.exec(instructionsArray[MA].instructions);
    instructionsFormat.font = tomatoBasefont.fontName;
                                  instructionsFormat.size = 14;
                                  textbox.defaultTextFormat = instructionsFormat;
                                  textbox.multiline = true;
                                  textbox.htmlText = instructionsArray[MA].instructions;
                                  textbox.width = 778;
                                  textbox.height = 340;
                                  //Testing Dictionary Search START
                                  //Search instructions for words in dictionaryArray
                                  dictionaryTimer.addEventListener(TimerEvent.TIMER, onTimer);
                                  dictionaryTimer.start();
                                  //Testing Dictionary Search END
                                  i_MC.x = 180;
                                  i_MC.y = 160;
                                  i_MC.name = "instructionBox";
                                  // Shadow Gray color;
                                  qbkg_shadow.graphics.beginFill(shadowColor);
                                  // x, y, width, height, ellipseW, ellipseH;
                                  qbkg_shadow.graphics.drawRoundRect(10, 10, 788, 351, 20, 20);
                                  qbkg_shadow.graphics.endFill();
                                  // Purple Box color;
                                  qbkg.graphics.beginFill(boxColor);
                                  // x, y, width, height, ellipseW, ellipseH;
                                  qbkg.graphics.drawRoundRect(0, 0, 788, 351, 20, 20);
                                  qbkg.graphics.endFill();
                                  xClose.addEventListener(MouseEvent.MOUSE_DOWN, mouseClickHandler);
                                  xClose.x = 750;
                                  xClose.y = 2;
                                  i_MC.addChild(qbkg_shadow);
                                  i_MC.addChild(qbkg);
                                  i_MC.addChild(textbox);
                                  i_MC.addChild(xClose);
                                  addChild(i_MC);

    And here is a "workable solution" - an example of how to deal with it.
    This class creates roll overs and tooltips for the search term.
    A lot of this code is based on what we discussed before - nothing really new.
    Just place this class in to FLA directory and make this class a Document Class in Flash IDE. I don't like Flash IDE and coding on the timeline - so it is up to you to translate it into  timeline code. Some aspects are commented in the code.
    package
              import flash.display.Sprite;
              import flash.events.MouseEvent;
              import flash.geom.Rectangle;
              import flash.text.TextField;
              import flash.text.TextFormat;
              public class TextRollOverExample extends Sprite
                        private var highlight:TextFormat = new TextFormat("Arial", 14, 0xff0000, null, true, true);
                        private var originalText:String;
                        private var tf:TextField;
                        private var inputField:TextField;
                        private var termBoundaries:Vector.<Rectangle>;
                        private var _searchTerm:String;
                        private var tipText:TextField;
                        public function TextRollOverExample()
                                  init();
                        private function init():void
                                  originalText = "I have a textfield that I am reading the content in from a XML file.  Is there a way to search said textfield for a certain word from an Array?  For Ex.  if I have a paragraph of text in the textfield and I want to search the textfield for a word that is in an array like 'The' and underline every instance of the word can I do that?";
                                  tf = new TextField();
                                  tf.defaultTextFormat = new TextFormat("Arial", 12);
                                  tf.multiline = tf.wordWrap = true;
                                  tf.width = 300;
                                  tf.autoSize = "left";
                                  tf.text = originalText;
                                  tf.x = tf.y = 50;
                                  addChild(tf);
                                  searchTerm = "textfield";
                        private function set searchTerm(term:String):void
                                  _searchTerm = term;
                                  tf.setTextFormat(tf.defaultTextFormat);
                                  var re:RegExp = new RegExp(term, "gi");
                                  var result:Object = re.exec(originalText);
                                  termBoundaries = new Vector.<Rectangle>();
                                  while (result)
                                            tf.setTextFormat(highlight, result.index, result.index + term.length);
                                            // get term boundaries and push them into collection of all related boundaries
                                            termBoundaries.push(tf.getCharBoundaries(result.index).union(tf.getCharBoundaries(result.index + term.length)));
                                            result = re.exec(originalText);
                                  drawHotSpots();
                        private function drawHotSpots():void
                                  // create hot spots for all
                                  for each (var rect:Rectangle in termBoundaries)
                                            hotSpot = rect;
                        private function set hotSpot(rect:Rectangle):void
                                  var s:Sprite = new Sprite();
                                  s.buttonMode = s.useHandCursor = true;
                                  s.addEventListener(MouseEvent.MOUSE_OVER, onHotSpotInteraction);
                                  s.addEventListener(MouseEvent.MOUSE_OUT, onHotSpotInteraction);
                                  s.graphics.beginFill(0xff0000, 0);
                                  s.graphics.drawRect(0, 0, rect.width, rect.height);
                                  addChild(s);
                                  // position hotspot over corresponding word
                                  s.x = tf.x + rect.x;
                                  s.y = tf.y + rect.y;
                        private function onHotSpotInteraction(e:MouseEvent):void
                                  switch (e.type)
                                            case MouseEvent.MOUSE_OVER:
                                                      drawTooltip(_searchTerm, Sprite(e.currentTarget));
                                                      break;
                                            case MouseEvent.MOUSE_OUT:
                                                      killToolTip();
                                                      break;
                        private function drawTooltip(term:String, target:Sprite):void
                                  killToolTip();
                                  tipText = new TextField();
                                  tipText.defaultTextFormat = new TextFormat("Arial", 11, 0x008000);
                                  tipText.width = 100;
                                  tipText.border = true;
                                  tipText.background = true;
                                  tipText.borderColor = 0x808080;
                                  tipText.autoSize = "left";
                                  tipText.multiline = tipText.wordWrap = true;
                                  tipText.text = "This thingy describes what " + term + " is.";
                                  addChild(tipText);
                                  tipText.x = target.x;
                                  tipText.y = target.y + target.height + 2;
                        private function killToolTip():void
                                  if (tipText)
                                            if (this.contains(tipText))
                                                      removeChild(tipText);
                                            tipText = null;

  • Obnoxious JTextPane and JScrollPane problem.

    I have written a Tailing program. All works great except for one really annoying issue with my JScollPane. I will do my best to explain the problem:
    The program will continue tailing a file and adding the text to the JTextPane. When a user scrolls up on the JScrollPane, the program still adds the text to the bottom of the JTextPane and the user can continue to view what they need.
    Here is the problem: I have text being colored throughout the text pane. For instance, the word ERROR will be in red. The problem is when the program colors the text, it moves the scroll pane to the line where word that was colored is at. I don't want that. If the user moves the scroll bar, I want the scroll bar to always stay there. I don't want the program to move to the text that was just colored.
    Is there a way to turn that off? I can't find anything like that anywhere.

    Coloring text will not cause the scrollpane to scroll.
    You must be playing with the caret position or something.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • HIGHLIGHTING WORDS AND DICTIONARIES SUPPORT - Search and highlight words in the PDF documents

    One of the things that Adobe people don't understand very well, is they focus and focus and focus constantly in adding new "cool" features to the product... as more flash support... etc. etc.
    But Adobe still pending to make easier the life of people that work with tons and literally tons of PDF documents.
    Students, researchers, law professors, academics... they all need a solution to search and highlight in different colors, for certain words in a lot of documents.
    So here we have a challenge for the Adobe folks.
    Let's imagine you are working in a Law Office, ok? (you're lawyer, not programmer)
    You have a trial tomorrow...
    The trial is about robbery (for example)
    Now you are looking for Jurisprudence (other similar cases that were judged before)...
    And let's imagine you have a folder with 200 cases in 200 PDF files, talking about robbery, between the years 2005-2009
    Now, let's imagine you are interested to search the words:
    CONVICTION
    KIDNAPPING
    ASSAULT
    FAILURE
    CRIME
    SUBPOENA
    How do you do that Adobe folks?
    Reading the 200 documents? one by one, having to drink all the ink of the documents, line by line...
    Or, could you, please, allow Adobe Acrobat 10 can handle dictionaries of words, and allow the users, to search and highlight those words in folder of PDF documents.
    Of course!!! you'll tell me, oh, you can accomplish a search of the desired words and Acrobat will search them for you in a lot of documents in a folder...
    And I'll reply you! oh! that is not enough!
    And do you know why?
    Just simpley because I need to see all the information highlighted in a context...
    If I see the word CRIME in red close to FAILURE... also in red I can see that something wrong is happening with that trial, for example...
    Do you understand now that searching single words in a lot of documents is not enough, and you have to improve URGENTLY this feature?
    Highlighting the words the users need to search in a folder of documents, allow INTENSIVE RESEARCH AND SAVE HOURS AND DAYS AND EVEN MONTHS OF HARD WORK TO THE USERS.
    In that way, you don't have to read the whole document, you just go directly to the highlighted parts.
    I've been submitting this feature since Adobe Acrobat 6!!!! No one in Adobe listened to me!!!
    I sincerely don't know why these forums are opened, must be an idea of someone from marketing, because finally, Adobe don't implement any specification from the users.
    I am absolutely sure, Adobe folks will present the 10 version as something pretty cool, with more flash support and more graphic stuff.
    But, as always, withouth helping the real people that work extensively with large amounts of documents.
    So I hope, Sirs, Madams of Adobe, please, now yes, you give support to this feature once and for all !!!
    Thanks

    Adobe does listen to users, but it listens to 10 users more frequently than 1 user. It listens to 1000 users more frequently than 10. Get everyone you know that works for lawyers to post the request in the Adobe wish form (where Adobe tabulates user requests).
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform
    Then maybe it will appear in Acrobat 11. If it is not in Acrobat 10 by now it is probably too late in the upgrade cycle for it to get in.

  • JTextPane and Horizontal Scrollbars

    Hi there,
    I had written an app that included an Event Log, and all was good in my
    world.
    Then one of the app users commented they would like errors to stand out within the log!
    I said "No Problem" but it turns out to be a major bloody headache!!!!!
    I was using a JTextArea but after reading some posts on this forum I decided to use a JTextPane. I found some code for changing the font colour, and everything appeared to be working fine ;-)
    ...until that is I realised my HORIZONTAL_SCROLLBAR_AS_NEEDED was never needed as the text had started to wrap ;-(
    I have tried searching this site and none of the suggestions work for me, the vertical scroll works fine - and I am really stuck. Therefore:
    Is there a way to get the Horizontal scroll bar working in a JTextPane?
    Is there an alternative to JTextPane that will allow me to control font colour by line?
    Do you even know what I am harping on about?
    Or should I admit defeat and add a second JTextArea and a button to switch between my two event types??
    Any suggestions would be greatly received!
    P.S. Below is the edited code that I think is responsible for my problem :0)
    public class EventLogGUI extends JPanel
    private JPanel jpLog = new JPanel();
    private StyledDocument sdLog = new DefaultStyledDocument();
    private JTextPane jtpLog = new JTextPane( sdLog );
    private MutableAttributeSet mas = new SimpleAttributeSet();
    private JScrollPane jspLog;
              public EventLogGUI()
              this.setBounds( 5, 7, 407, 256 );
              this.setBorder( BorderFactory.createLoweredBevelBorder() );
              this.setLayout( null );
              this.add( jpLog );
              jspLog = new JScrollPane( jtpLog,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
              jspLog.setBounds( 12, 25, 372, 180 );
              jpLog.setLayout( null );
              jpLog.setBounds( 5, 5, 397, 218 );
              jpLog.add( jspLog );
              jtpLog.setEditable( false );
              jtpLog.setMargin( new Insets ( 2, 2, 2, 2 ) );
              public void initialiseGUI()
              Vector events = uploadEventLog();
              String event;
              jtpLog.setText( "" );
                        for ( int i = 0; i < events.size(); i++ )
                        event = "" + events.elementAt( i );
                                  if ( event.length() >= 8 && event.substring( 0, 8 ).equals( "WARNING:" ) )
                                            StyleConstants.setForeground( mas, Color.red );
                                  else
                                            StyleConstants.setForeground( mas, Color.black );
                                  try
                                  sdLog.insertString( sdLog.getLength(), event + "\n", mas );
                                  catch( Exception e )
    }

    Hi!
    just wondered if you've searched the forum already. If not: always do that before posting.
    I searched and found this helpful:
    http://forum&threadID=256602
    the solution found in that thread is to extend the JTextPane and add a setLineWrap-method:
    class JTextWrapPane extends JTextPane {
        boolean wrapState = true;
        JTextArea j = new JTextArea();
         * Constructor
        JTextWrapPane() {
            super();
        public JTextWrapPane(StyledDocument p_oSdLog) {
            super(p_oSdLog);
        public boolean getScrollableTracksViewportWidth() {
            return wrapState;
        public void setLineWrap(boolean wrap) {
            wrapState = wrap;
        public boolean getLineWrap(boolean wrap) {
            return wrapState;
    }  now you can use JTextWrapPane instead of JTextPane:
    //  instead of   private JTextPane jtpLog = new JTextPane( sdLog );
        private JTextWrapPane jtpLog = new JTextWrapPane( sdLog );and set JTextWrapPane.setLineWrap(false):
            jtpLog.setLineWrap(false);It may not be the non plus ultra, but it seamed to work for me. ;)

  • Where are the shadows and highlights sliders?

    Just confirming that they eliminated the 2 most useful editing sliders. And the option to edit in an external editor is gone, too? This app is not ready for prime time.

    The Shadow and Highlight sliders are in the optional set, that you have to reveal.
    In the Edit panel open the adjustments.
    If you do not see "Light" adjustments, click the blue "Add" text.
    In the Light Adjustments, click the down arrow beside "Auto".
    Now you will see several sliders for light values.

  • JComboBox selection and highlight problem of the selected item

    Hi,
    I have a question how can I make my newly added item to the combo-box selectable and highlighted. I am adding new items to my custom comboBox dynamically and I want whatever item I add to be selected by default. I am using my own custom ComboBoxModel that extends AbstractListModel and implements ComboBoxModel and TreeModelListener, and my custom Renderer that extends JLabel and implements ListCellRenderer. Because I am trying to get a tree structure in my comboBox model and that's why I have my own custom model and renderer. Now when I add a new node or item to my comboBox it is being added and shown in the combo-box textField, but as soon I pull down the combo-box my parent directory is selected though my current selection is the last node added. That's how I am adding new nodes and making it selectable
    treeModel.insertNodeInto(tempNode, (DefaultMutableTreeNode)nodeCollection.lastElement(), 0);
    int nodeTotal =((CMRGlobals.myTreeGlobals).getModel()).getSize();
    Object lastNode = CMRGlobals.myTreeGlobals).getModel()).getElementAt(nodeTotal - 1);
    ((CMRGlobals.myTreeGlobals).getModel()).setSelectedItem(lastNode);
    when I do this my node is added under my parentNode and is shown in the comboBox but when I try to pull down the combo my parent node is high lighted and when I move out of the combo-box my parent node gets selected and show in the combo-box though I haven't selected it,and the contents of my last node are shown. I am just writing my own custom model that simulates the effect of JTree. I am using these......
    DefaultMutableTreeNode and
    DefaultTreeModel
    and in my JComboBox I am setting my model as
    this.setModel(new myModel(treemodel));
    this.setRenderer(new myRenderer());
    I am building my own FileDialog that just works like FileDialog I have all the functionality except this problem.Thanks for any help. I know I have posted this same thread yesterday but I didn't get any response hoping now may somebody can help me.Thanks again

    never mind I got it
    Thanks

  • IPhoto 9.4 sliders for shadows: and highlights: only give black page. can anyone help?

    iPhoto 9.4 sliders for shadows: and highlights: only give black page. can anyone help?

    While we all have MacBooks in this forum not all of us use iPhoto. There's an iPhoto Support Community where everybody uses iPhoto. You should also post this question there to increase your chances of getting an answer.   https://discussions.apple.com/community/ilife/iphoto

Maybe you are looking for

  • Caching credentials for webauth in ISE 1.2?

    We are providing internet access through a Guest portal. The portal is provided by the ISE through webauth and the user is created through the ISE Sponsor Portal. When an account is created and the enduser logs in to it, I would like for the ISE to c

  • I updated the maverick and now mail won't open at all

    i updated the maverick and now mail won't open at all

  • Error while configuring APEX

    I have completed the installation of APEX and HTTP server on an instance. But while configuring , I got the following error in the login page. Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance

  • Getting appmod reference in UIX controller class

    Hi, I tried using ServletBindingUtils.getApplicationModule(BajaContext) method in a static method in UIX controller class to get the reference of application module defined in UIX page. But i am getting null. How can i get the reference of view and a

  • Administrator Account

    I recently got my daughter's PowerPC. When she first got it she set it up with her name as the administrator, her home folder is in her name, etc. I have not changed it for some time but I finally decided that I might like to do it. My question is ho