JTextPane Colour Highlighting

Im doing up a prototype of a compiler, i have certain keywords like "if"s and "elses" etc etc which i would like to be colour coded differently!!! My problem is when i have big files the time it takes to colour code and display is horrendous!!! I just want to know am i going about the right way in highlighting my keywords?? is there a better way or how can i improve my current code!!! any suggestions at all are welcome!! heres a sample of code..
public class MyDoc extends DefaultStyledDocument
static MutableAttributeSet setAttr, ifAttr, defaultAttr;
public MyDoc()
setAttr = new SimpleAttributeSet();
StyleConstants.setForeground(setAttr, Color.red);
ifAttr = new SimpleAttributeSet();
StyleConstants.setForeground(ifAttr, Color.blue);
defaultAttr = new SimpleAttributeSet();
StyleConstants.setForeground(defaultAttr, Color.black);
public void insertString(int offs, String str, AttributeSet a) throws
BadLocationException
if (str == null) return;
StringTokenizer tokenizer = new StringTokenizer(str," \n",true);
try
while( tokenizer.hasMoreTokens())
String token = (String)tokenizer.nextElement();
if(token.length() == 0)
continue;
if (token.compareTo("set") == 0)
super.insertString(offs, token, setAttr);
} else if (token.compareTo("if") == 0)
super.insertString(offs, token, ifAttr);
} else
super.insertString(offs,token, defaultAttr);
offs = offs + token.length();
} catch (BadLocationException ble)
System.err.println("MyDoc::insertString()"+ble.toString());
}catch(Exception e)
System.err.println("MyDoc::insertString()"+e.toString());
bottom line is that im looking for some other way, more elegant way of getting keywords highlighted, the above is nasty!!!
cheers people,
JB.

I have tried a couple of different approaches for using threads:
1) Load the data into the text pane and then use a thread for highlighting. The highlighting got messed up if you type data in the text pane while the highlighting thread is working. This approach won't work with the current structure of the SyntaxDocument.
2) Load data into the text pane in smaller pieces. This approach shows a little more promise as the text pane is shown with initial data in a couple of seconds. However, the entire load time goes from 15 to 26 seconds. During this 26 second load time you can type data and scroll, but the text pane reacts very slowly. I haven't verified that data inserted into the document by typing does not cause problems with data being loaded into the document by the background thread. (Swing components are not thread safe, but hopefully insertion of data into the document is). Here is the test class:
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
public class LoadTextPane extends JFrame
     char[] data;
     JTextPane textPane;
     public LoadTextPane(String fileName)
          EditorKit editorKit = new StyledEditorKit()
               public Document createDefaultDocument()
                    return new SyntaxDocument();
          textPane = new JTextPane();
         textPane.setEditorKitForContentType("text/java", editorKit);
         textPane.setContentType("text/java");
          JScrollPane sp = new JScrollPane(textPane);
          getContentPane().add( sp );
          long startTime = new Date().getTime();
          try
               File f = new File( fileName );
               FileReader in = new FileReader( f );
               int size = (int) f.length();
               data = new char[ size ];
               int chars_read = 0;
               while( chars_read < size )
                    chars_read += in.read( data, chars_read, size - chars_read );
               in.close();
               long endTime=new Date().getTime();
               System.out.println( "File size: " + chars_read );
               // System.out.println( data );
          catch (IOException sse)
               System.out.println("Error has occured"+sse);
          System.out.println( "Time to read file: " + (new Date().getTime() - startTime ));
          if (data.length > 8092)
               Thread load = new LoadThread(data, textPane.getDocument());
               load.start();
          else
               textPane.setText( new String(data, 0, data.length) );
     public static void main( String[] args )
          String fileName = "c:/java/jdk1.3/src/java/awt/Component.java";
          JFrame f = new LoadTextPane(fileName);
          f.setDefaultCloseOperation( EXIT_ON_CLOSE );
          f.setSize( 1000, 600);
          f.setVisible(true);
     class LoadThread extends Thread
          char[] data;
          Document doc;
          LoadThread(char[] data, Document doc)
               this.data = data;
               this.doc = doc;
          public void run()
              int start = 0;
              int end = data.length;
              int increment = 8192;
               long begin = System.currentTimeMillis();
              while ( start < end )
                   if (start + increment > end)
                        increment = end - start;
                   String text = new String(data, start, increment);
                   try
                        doc.insertString(doc.getLength(), text, null);
                   catch(BadLocationException e)
                        System.out.println(e);
                   start += increment;
                    //  allow some time for the gui to process typed text, scrolling etc
//                    try { Thread.sleep(300); }
//                    catch (Exception e) {}
               System.out.println( "Load Text Pane: " + (System.currentTimeMillis() - begin) );
}

Similar Messages

  • 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. =)

  • Please could someone tell me how to insert colour into my calendar text, especially coloured Highlights. Thanks.

    please could someone tell me how to insert colour into my calendar text, especially coloured Highlights. Thanks.

    Another netbook is not a desktop computer.
    Have you transferred your iTunes library from the backup for the laptop that died along with all other important data to the new computer such as documents, photos, etc.?
    If not, all iTunes content on your iPhone will be erased as the first step when syncing the iPhone with iTunes on a new or different computer.
    Have you launched iTunes on the new computer?
    Is you iPhone avaialble under Devices in the iTunes source list on the new computer?

  • Green and purple coloured highlights

    I am getting green and puple colours all over my raw photos where highlights are present, like on  wet objects such as pebbles on a beach, I don't get this using lightroom so it isn't a camera problem. I use a number of cameras and it happens on all my files from any of my 7 cameras. I have resorted to using Lighroom because of this problem for the time being so any help would be very much apreicated.

    Have you tried the Raw Fine Tuning Adjustments?
    Try to adjust Hue Boost, Boost, or Moire.

  • 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.

  • JTextPane &  XML highlighter

    Hello,
    I wrote an XML Viewer via JTextPane.
    Unfortunately I don't know how to implement a good XML highlighter.
    I wrote an own code using the regulary expression.
    With the regulary expression I can get the "startPosition" and "endPosition"
    of pattern I am searching for within a text.
    StyledDocument xmlDoc;
    xmlDoc.setCharacterAttributes(startPosition, length,  style, true);It is working very good for xml files up to ca. 1000 ... 1200 lines.
    But for bigger files it takes too long until the highlighting took place.
    1) Is there another faster mechanism to highlight xml files?
    2) How do I wrap / unwrap the horizontal display without re-reading or re-highlighting the xml file again?
    Thanks Aykut

    Interesting. I will keep that in mind.
    I have more or less got what i need working now - just smoothing out some bumps.
    Extending DefaultHighlighter cannot help much as to override paint() is near impossible because required info is private in the superclass :(
    But I could hold my own highlight info there for one highlight type and paint those first before calling super.paint(). Looking back, I should have replaced the whole highlight system - that would have been easier and neater.

  • Printing cross reference colour highlights InDesign CC

    I am using cross references in InDesign CC and a different colour for each. Is it possible to print these from InDesign?

    I believe you already have the settings for PDF appearance set in the Cross references dialog.
    If you do and are still not seeing the result in the PDF then you need to turn on the setting of Hyperlinks on.
    Thanks
    Javed

  • JTextPane selection Highlighting

    I have got a next problem.
    I have got text editor that uses JTextPane. When I select text and try change font (choose ComboBox with Font names) my text selection is hide and I mush execute textPane.grabFocus(); to take back selection.
    How can I make so as this selection is not hide?

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=317332

  • No data found in csv output

    I have a classic (non-interactive) report that shows some strange behaviour.
    It's a simple page with a report region.
    On the report attributes page under 'report export' the value for 'Enable CSV output' is set to 'Yes' and 'Link label' has a meaningful discription.
    In the development database it works as expected:
    When I run the page the data is displayed and when I click the link for csv output I can either save or open the file. In both cases I find the data I expect in the csv file.
    In production, however, when I run the page the data is displayed, but when I click the link for csv output the resulting csv file just shows "No Data Found"
    I can imagine the report not returning any data, but in that case I shouldn't see any data on screen either.
    And it's extra weird that in development it all works fine.
    Anybody that can offer any help?
    Thanks in advance.

    Hi Eric
    I would never dream of telling anyone not to argue with me :D I've been wrong before and will be again, no doubt!
    For the DIV problem, I was more concerned with &lt; appearing in the output rather than the SQL statement itself - generally problems such as this happen when something on the page is incorrectly formed. When you get a chance, in FireFox, install the Web Developer add-on. When this is installed, on the right-hand end of its toolbar, you will see three buttons - the last two tell you about css and javascript errors. For HTML errors, if you have a text editor that has syntax highlighting, do a View Source on the loaded page, take a copy of the source and paste it in to a new document in the text editor. Save this with an HTML file extension. This should colour-highlight everything. It should become obvious what is wrong as you tend to end up with way too much in the same colour. Finally, on the loaded page, right-click on the DIV text and select Inspect Element - this switches you to a heirarchical view of the HTML on the page in the FireBug pane. Follow the tree up from the DIV and have a look at the structue - at some point, something will look wrong.
    Andy

  • Report Structure based CKF percentage total colume Error

    Dear Guru's
    In Report Created structure in Rows structure created formulas for sub total, CKF using in colume for finding percentage on sale,
    where formula used in structure, percentage also adding instead of average. Applied exception aggregation for plant but no result
    Example scenario : Zone1 created with selection of plant, division and region.same as a UCWL and internal total Zone1+UCWL used formula
    percentage CKF working as addition. Red colour highlighted are wrong totals
    Month
    Target
    Prorata
    Target
    Actuals
    Today
    Actual
    Todate
    %Age
    Achiev
    Target
    PPC % age
    PPC %Age
    Actual
    Rajasthan Zone1
    45,000
    36,000
    1,276
    27,473
    76
    67
    54
    UCWL
    25,000
    20,000
    952
    18,183
    91
    100
    76
    ZONE1+UCWL Total
    70,000
    56,000
    2,228
    45,656
    167
    167
    129
    Rajasthan Zone 2
    60,000
    48,000
    1,722
    34,746
    72
    65
    10
    Rajasthan Total
    1,30,000
    1,04,000
    3,950
    80,403
    240
    232
    140
    Gujarat-Sirohi
    1,12,000
    89,600
    2,555
    85,877
    96
    42
    Gujarat-Kalol
    60,000
    48,000
    1,644
    34,945
    73
    75
    30
    Gujarat- P Pur
    8,000
    6,400
    247
    6,035
    94
    100
    Gujarat Total
    1,80,000
    1,44,000
    4,447
    1,26,857
    263
    217
    30
    Treat this most urgent, report is pending due to percentage total.
    Regards
    ramesh

    I applied this:
    If([Process Category] InList("Process01") And IsNull([Date]);[Percentage];Max(Date)))
    [Percentage] = (Count([Date])/Count([Operation]))*100.
    but, this is not becoming true - even when Operation has one Date
    Showing result as:
    List#,Process01,Process02
    100, 11/12/2010, 11/15/2010
    But result should be
    100,50%,11/15/2010
    Can anyone help me achieve the right result!
    Thanks in advance.

  • State transitions across components?

    Hi,
    I've been using Catalyst for a few days now to put together a "clickable mockup" of an app. Instead of working based on a comp, I'm creating the UI in Catalyst directly, using it's built-in components and creating a "wireframe" look. Works fine. I anticipate to work with more hi-fi comps.
    One thing I'm having trouble with, is making deep transitions between states from subcomponents.
    Imagine this setup:
    The app has two states/pages, "1" and "2". Inside each page, I have one component to represent all the states of that page. So for the first page, the internal component states would be 1-1, 1-2 and 1-3. Ditto for 2.
    So, now, let's say that in state 1-3, I have a button inside the component, where I want to transition to 2-2. Currently, it appears that there is no way for me to do that. When I click on the options in "Play transition to state" of the button, it shows me states 1 and 2, as well as 1-1 through 1-3, but it does not show the "child" states of "2".
    Is there any way to accomplish the transition from 1-3 to 2-2?
    Another version on the same problem: let's say I can somehow get from 1-3 to 2-2. Now, inside 2-2, I have a button that jumps back to "1". Currently, when I jump to "1", it jumps to whatever state 1 was in, which is 1-3 in my case, which is undesirable. It would be nice if I could somehow reset the component state on some event (showing, hiding, ...) to its default state, so that when people later jump back to it, it would start in its default state.
    I am familiar with ActionScript and XML and did poke around a bit. I see that in components, there is this kind of code:
      protected function Button_click_1_1():void
        mx.core.FlexGlobals.topLevelApplication.currentState='AppHome';
    I speculate that this lets me do what I need by editing code, and instead of topLevelApplication.currentState using topLevelApplication.someComponent.currentState... but I wanted to see if there is/will be another friendlier way of accomplishing this?

    Hi,
    Just my, hopefully helpful thoughts about how to render complex state transition much easier to understand, design and debug ...............
    Perhaps, initially for coders with a solid background in conditional logic, the inclusion of one or two design windows/panels providing the ability to design and display at least state transition diagrams and preferably also state transition tables, could be very helpful when trying to either design or understand complex, inter-related state transitions - actually, even relatively simple state-transitions with only five to seven objects, each with only three or four states to track concurrently, can be difficult to design, debug and test using just a mental model and memory to retain knowledge of the desired vs. actual state transition paths.
    Although I say "initially for coders", many years ago I taught both of these techniques successfully during software "design principles" courses that addressed software developers who's function was to prepare "design specifications" rather than actually write the code which, in those days, was the job of programmers rather than designers.  In fact many of my students were not programmers at all - for example analysts who used state transition diagramming techniques to design functions regardless of whether those functions would become implemented as code, or as a set of human actions, or mechanical machine operations (think pinball!).
    It should be possible using today's technoloy to be able to
        (a) generate code from a state transition table or a state transition diagram and
        (b) generate both forms of diagram from existing code (including the code autogenerated during visual design and
        (c) consistency check existing code automatically.
    It should be possible, using state transition table and diagram functions, to highlight structural logic errors.  How such highlighting should be done, for example:
        (a) using a classic state transition table or diagram or
        (b) generating some form of structured text report or
        (c) inserting colour-highlighted error messages in-line in the code or
        (c) some other more visual-designer-oriented signalling technique or
        (d) a combination of several of the above
    would be a design issue for Adobe.  This would not be a trivial exercise for Adobe, but the functionality would be reusable, i.e. transferable into other products.
    After all, the only reason for such tables or diagrams is to render complex state transitions understandable by humans, and these two techniques have proved extremely useful for many decades in many areas of design - programming, electronic circuit design, machine design, business process design......
    Re. Catalys, it's just a classic program design application, with some whizzy UI graphics that need to display, disappear, change colour, glow, shimmer, move, .... in predictable and desirable ways.
    The original pinball machines used mechanical relays to implement their underlying state transition diagrams; pinball designers needed to understand at least two things (a) complex state transitions and (b) a well designed UI. From this point of view, Catalyst looks like a pinball design panel!

  • Set color in TextArea for certain String

    I need to highlight some Strings in different color than the setForeground() in the TextArea. Is it possible and how can I accomplish it?
    Help is great appreciated.
    Anna

    I am able to use JTextPane to highlight certain string now.
    Thanks a lot.
    Though I am having problem on mouse double click on a file name.
    For TextArea, the getSelectedText() will pick the full path name of the file. For JTextPane, the selected text is just part of the string.
    Following is the text:
    Test report is saved in file C:\tests\pf2150\JTAG\888_test.rpt
    The file name is
    C:\tests\pf2150\JTAG\888_test.rpt
    My mouse is over the file name but double click only picks JTAG or pf2150 or ...
    Could anybody help?
    Anna

  • Embedding a JButton in a JTextArea or JLabel.

    Hi,
    I am trying to figure out how to integrate a JButton into a text block.
    The idea is that the user is presented with instructions on how to solve a problem for instance how to switch on standby electric power when operating a generator.
    The instructional text would have a colour-highlighted text string, lets say STANDBY ELECTRIC POWER "embeded" at the appropriate place and the user clicks on it to access the detailed instructions of how to switch on this case standby electric power.
    The instruction could look something like the following:
    "If the generator voltage drops below a minimum of 24 volts switch on the STANDBY ELECTRIC POWER and ensure that the voltage is 28 volts".
    Clicking on this text string would then direct the user to a detailed explanation of how he/she should proceed to get and monitor standby electric power.
    I image that using a JLabel or JTextArea and "embeding" a JButton at exactly the place indicated would do the job. Maybe there is a better way???
    Does anyone have any ideas?
    Many tks
    John

    Use a JEditorPane and add a HyperLinkListener. The API has an example.

  • N85 display clarity problem

    hai friends i have just taken Nokia N85. this mobile display is very reddish. videos and photos all are displaying with red colour highlightly. i asked the sales man about that. he said it is OLED display. the model is coming with reddish display.
    is it true?
    Solved!
    Go to Solution.

    Is it made in Finland?
    I don't mean to joke, but I think mine is just fine concerning color and I disagree that "red-ish" is that noticable. I agree that colors are deep, but without the red hues in them.
    wait, let me check....
    red in everything is bull. I checked a bunch of pictures, all the colors are what they are. although I noticed one thing that might be part of this subject. My pictures taken in low light or at night show just a tiny red hue where the picture has black colors. I mean, the black grounds in my pictures show a tiny red-ish hue that doesn't even catch your eye to question.
    Other than pictures, black is black and I don't want my baby back..
    Peace
    Does Nokia have product Beta-Testing nowadays?

  • Javascript syntax error (slashes) *invalid*

    Hi, ive had this before and now again and cannot get it to understand it correctly and i do not know the solution?
    I have this simple calculation:
    var myVar = myRound((20*1000/100),3)+" kg/hr";
    Notice this has 2x / one for division and one in the unit str but DW colour highlights part of this as something else (regex?) and causes the error warning?
    Do i now have to carry on with my code with incorrect code hints and a constant sysntax error warnring?
    Thanks
    Andy

    Try breaking that line up like this -
    var myVar = (1000/100);
    myVar = myRound((20*(myVar)),3)+" kg/hr";

Maybe you are looking for