• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 525
  • Last Modified:

Help me optimize jtextpane

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
kvarkkvark
Asked:
kvarkkvark
  • 2
  • 2
1 Solution
 
mightyoneCommented:

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
 
kvarkkvarkAuthor Commented:
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
 
mightyoneCommented:

just

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

so check if lastcolor = oldcolor replaceSelection (s)
else append othercolor
0
 
kvarkkvarkAuthor Commented:
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
 
Dejan PažinHead of SW DevelopmentCommented:

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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now