?
Solved

Help me optimize jtextpane

Posted on 2005-04-21
5
Medium Priority
?
520 Views
Last Modified: 2008-01-09
Provided a working class with mainfile (StillLife), all it does is it writes out a with 2 diffrent colors to a text pane, and in System.out print out the time it took to write those a's out. As you can see it's very slow ): Need another aproach to solve this problem, please help!

What i would like to do is connect a telnet stream to this, but as you know telnet uses ansi color codes
and with this slow colored text performance of the jtextpane it  results in a slow telnet application.

output from system out...
Execution took:625 ms
Execution took:1140 ms
Execution took:1687 ms
Execution took:2031 ms
Execution took:2780 ms
Execution took:3531 ms
Execution took:3983 ms
Execution took:4609 ms
Execution took:750 ms
Execution took:406 ms
Execution took:1062 ms
Execution took:1718 ms
Execution took:750 ms
Execution took:2421 ms
Execution took:3593 ms

//Code start here
//----------------------------------------------------------
// ColorPane.java
// A simple extension of JTextPane that allows the user to easily append
// colored text to the document.
//

import java.io.InputStream;
import java.io.PrintStream;

import java.util.*;

import org.apache.commons.net.telnet.TelnetClient;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.Color;

public class StillLife

    extends JTextPane {
  private TelnetClient telnet = new TelnetClient();
  private InputStream in;
  private PrintStream out;
  private StringBuffer sbBuffer = new StringBuffer();


  public StillLife (){
   sbBuffer.append("a ");
   final Random generator2 = new Random( 121 );
    System.out.println( generator2.nextBoolean());
    Thread thread = new Thread() {
    public void run() {
     
      int number = 0;
      while(true)
      {
       
        try {
          Thread.sleep(3000);
        }
        catch (InterruptedException ex) {
          System.out.println(ex.toString());
        }
         long start = System.currentTimeMillis();
        number = 0;
            while (number++ < 400){
              if(generator2.nextBoolean())
              append(Color.red, sbBuffer.toString());
            else
                append(Color.green, sbBuffer.toString());
            }
            System.out.println("Execution took:" + (System.currentTimeMillis() - start) + " ms");
      }
    }
  };
  thread.start();

  }


  public void appendNaive(Color c, String s) { // naive implementation
    // bad: instiantiates a new AttributeSet object on each call
    SimpleAttributeSet aset = new SimpleAttributeSet();
    StyleConstants.setForeground(aset, c);

    int len = getText().length();
    setCaretPosition(len); // place caret at the end (with no selection)
    setCharacterAttributes(aset, false);
    replaceSelection(s); // there is no selection, so inserts at caret
  }

  public void append(Color c, String s) { // better implementation--uses StyleContext
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                                        StyleConstants.Foreground, c);

    int len = getDocument().getLength(); // same value as getText().length();
    setCaretPosition(len); // place caret at the end (with no selection)
    setCharacterAttributes(aset, false);
    replaceSelection(s); // there is no selection, so inserts at caret

  }

  public static void main(String argv[]) {

    StillLife pane = new StillLife();
    JFrame f = new JFrame("ColorPane example");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(new JScrollPane(pane));
    f.setSize(600, 400);
    f.setVisible(true);



  }

    }

//Code ends here
//----------------------------------------------------------
0
Comment
Question by:kvarkkvark
  • 2
  • 2
5 Comments
 
LVL 6

Expert Comment

by:mightyone
ID: 13832168

resue your Object Stylecontext and just alter color and text

Object initialisation is expensive or create one for each colour and just alter text
0
 

Author Comment

by:kvarkkvark
ID: 13832205
Hello and thanks!

Tried that (se new code)

result is now:

Execution took:4547 ms
Execution took:1281 ms
Execution took:2032 ms
Execution took:2734 ms
Execution took:2844 ms

Still way to slow(assuming i did what you mentioned)

// ColorPane.java
// A simple extension of JTextPane that allows the user to easily append
// colored text to the document.
//

import java.io.InputStream;
import java.io.PrintStream;

import java.util.*;

import org.apache.commons.net.telnet.TelnetClient;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.Color;

public class StillLife

    extends JTextPane {
  private TelnetClient telnet = new TelnetClient();
  private InputStream in;
  private PrintStream out;
  private StringBuffer sbBuffer = new StringBuffer();
  private StyleContext sc = null;

  public StillLife (){
   sbBuffer.append("a ");
   final Random generator2 = new Random( 121 );
    System.out.println( generator2.nextBoolean());
    Thread thread = new Thread() {
    public void run() {
     
      int number = 0;
      while(true)
      {
       
        try {
          Thread.sleep(3000);
        }
        catch (InterruptedException ex) {
          System.out.println(ex.toString());
        }
         long start = System.currentTimeMillis();
        number = 0;
            while (number++ < 400){
              if(generator2.nextBoolean())
              append(Color.red, sbBuffer.toString());
            else
                append(Color.green, sbBuffer.toString());
            }
            System.out.println("Execution took:" + (System.currentTimeMillis() - start) + " ms");
      }
    }
  };
  thread.start();

  }


  public void appendNaive(Color c, String s) { // naive implementation
    // bad: instiantiates a new AttributeSet object on each call
    SimpleAttributeSet aset = new SimpleAttributeSet();
    StyleConstants.setForeground(aset, c);

    int len = getText().length();
    setCaretPosition(len); // place caret at the end (with no selection)
    setCharacterAttributes(aset, false);
    replaceSelection(s); // there is no selection, so inserts at caret
  }

  public void append(Color c, String s) { // better implementation--uses StyleContext
    if(sc == null)
    sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                                        StyleConstants.Foreground, c);

    int len = getDocument().getLength(); // same value as getText().length();
    setCaretPosition(len); // place caret at the end (with no selection)
    setCharacterAttributes(aset, false);
    replaceSelection(s); // there is no selection, so inserts at caret

  }

  public static void main(String argv[]) {

    StillLife pane = new StillLife();
    JFrame f = new JFrame("ColorPane example");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(new JScrollPane(pane));
    f.setSize(600, 400);
    f.setVisible(true);



  }

    }
0
 
LVL 6

Expert Comment

by:mightyone
ID: 13832873

just

replaceSelection(s);
must be altered on most cases!

so check if lastcolor = oldcolor replaceSelection (s)
else append othercolor
0
 

Author Comment

by:kvarkkvark
ID: 13832928
Thanks, but  once i use ansi the % the same color will be reused it very slight. So i need something that it fast even if i need to change color on every single letter.

0
 
LVL 17

Accepted Solution

by:
Dejan Pažin earned 1500 total points
ID: 13834096

I've corrected your code. The problem is, that you are updating swing components from another thread without using SwingUtilities.invokeLater, and I also added some other modifications (not using replaceSelection etc.)

On my computer the results are:
Execution took:165 ms
Execution took:123 ms
Execution took:41 ms
Execution took:74 ms
Execution took:26 ms
Execution took:20 ms


// ColorPane.java
// A simple extension of JTextPane that allows the user to easily append
// colored text to the document.
//

import java.io.InputStream;
import java.io.PrintStream;

import java.util.*;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.Color;

public class StillLife extends JTextPane
{
   //private TelnetClient telnet = new TelnetClient();
   private InputStream in;
   private PrintStream out;
   private StyleContext sc = null;

   AttributeSet a1;
   AttributeSet a2;

   public StillLife()
   {
      final Random generator2 = new Random(121);
      System.out.println(generator2.nextBoolean());
      Thread thread = new Thread()
      {
         public void run()
         {
            replaceSelection("start: ");
            if (sc == null)
               sc = StyleContext.getDefaultStyleContext();
            if (a1 == null)
            {
               a1 = sc.addAttribute(SimpleAttributeSet.EMPTY,  StyleConstants.Foreground, Color.red);
               a2 = sc.addAttribute(SimpleAttributeSet.EMPTY,  StyleConstants.Foreground, Color.green);
            }
            while (true)
            {
               try
               {
                  Thread.sleep(3000);
               }
               catch (InterruptedException ex)
               {
                  System.out.println(ex.toString());
               }

               SwingUtilities.invokeLater(new Runnable(){
                  public void run()
                  {
                     long start = System.currentTimeMillis();
                     StyledDocument sd = (StyledDocument)getDocument();

                     int number = 0;
                     while (number++ < 400)
                     {
                        try
                        {
                           if (generator2.nextBoolean())
                           {
                              sd.insertString(sd.getLength(), "a ", a1);
                           }
                           else
                           {
                              sd.insertString(sd.getLength(), "a ", a2);
                           }
                        }
                        catch (Exception e)
                        {
                           e.printStackTrace();
                        }
                     }
                     System.out.println("Execution took:" + (System.currentTimeMillis() - start) + " ms");
                  }
               });

            }
         }
      };
      thread.start();
   }


   public static void main(String argv[])
   {

      StillLife pane = new StillLife();
      JFrame f = new JFrame("ColorPane example");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setContentPane(new JScrollPane(pane));
      f.setSize(600, 400);
      f.setVisible(true);
   }

}
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month13 days, 18 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question