?
Solved

inconsistent text_entry.replaceText

Posted on 1997-06-25
7
Medium Priority
?
441 Views
Last Modified: 2012-08-13
I have a LiveConnect situation where selected text in a java textarea is passed to javascript, manipulated, and then sent back to the textarea to replace the selected text.

As the documents being edited become longer and more replaces are done, the results become more inconsistent.

INTENT -- what I'm trying to achieve after selecting the text between the HTML tags and then adding the tags.  The actual result is shown below.

For example, it starts like this:

INTENT: <B>56789</B>
1234<B>56789</B>012345678901234567890
INTENT: <B>def ghi jkl</B>
abc <B>def ghi jkl</B> mno pqr stu vwx yza bcd

Then it starts looking like this (missing end tag):

INTENT: <B>56789</B>
1234<B>56789012345678901234567890
INTENT: <B>def ghi jkl</B>
abc <B>def ghi jkl mno pqr stu vwx yza bcd

and then like this (offsetting by 4 often, but other amounts at other times):

INTENT: <B>56789</B>
12345678<B>56789</B>45678901234567890
INTENT: <B>def ghi jkl</B>
abc def ghi<b>ghi jkl</B> pqr stu vwx yza bcd

and then sometimes it is random like this:

INTENT: <B>56789</B>
1234567890123<B>56789</B>901234567890
INTENT: <B>def ghi jkl</B>
abc def ghi <B> def ghi jkl</B>stu vwx yza bcd

INTENT: <B>56789</B>
1234567890123<B>56789</B>901234567890
INTENT: <B>def ghi jkl</B>
abc def ghi j<B>def ghi jkl</B>stu vwx yza bcd

(These lines follow one another)

Computers aren't supposed to do this.  Any idea what is going on?

Thank you so much,

Anthony Krinsky
0
Comment
Question by:askrinsky
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222158
It looks like the kind of junk you would get in C when you don't initiate a local variable properly. Like the stuff thats left over in the stack from other calls apperently corrupts information in a string.

Are you initializing the variable you are using between succesive call?

Problems with live connect do exist, but they are usualy related to verry large buffer transfers, multiple GIF's and the like.

Based on the info you posted, thats about as good a guess as I can hazzard. Can you post code, both the JavaScript and the method? In lieu of that could you e-mail code?
0
 

Author Comment

by:askrinsky
ID: 1222159
Hey JPK --

I'd be happy to e-mail code, but I don't have your e-mail address.

I'm pretty sure the problem is with Java and may have several dimensions.  The first oddity is that selectText works fine... all the time...  The second oddity is that the Java problems get increasingly serious when more stuff (HTML tags and newlines vs. just text and returns that I type in myself) is added to the text-area and more replace actions are done... My friend suggested that one of the errors is that Java counts \n and \r as two characters on the write process, one on the read.. but that wouldn't explain everything.

Here are the hooks in JavaScript:

function getReplacementText() {
            var temp_value = '';
        temp_value = document.variables.ReplacementText.value;
        return temp_value;
}
function getInsertText() {
            var temp_value = '';
        temp_value = document.variables.InsertText.value;
        return temp_value;
}
function getAppendText() {
            var temp_value = '';
        temp_value = document.variables.AppendText.value;
        return temp_value;
}

.. and ..

<INPUT TYPE="hidden" NAME="SelectedText" value="">
<INPUT TYPE="hidden" NAME="AllText" value="">
<INPUT TYPE="hidden" NAME="ReplacementText" value="">
<INPUT TYPE="hidden" NAME="InsertText" value="">
<INPUT TYPE="hidden" NAME="AppendText" value="">

Here's the Java code for the text area...

/*
    A basic extension of the java.applet.Applet class
 */

import netscape.javascript.JSObject;
import java.awt.*;
import java.applet.*;

public class is_textarea_small_applet extends Applet {
      
      
    JSObject win;
    String text_entry_bak = "";
    StringBuffer text_entry_bak_buff = new StringBuffer(text_entry_bak);
    String text_entry_bak_JAVA = "";
    StringBuffer text_entry_bak_JAVA_buff = new StringBuffer(text_entry_bak_JAVA);
    String selected_text_buff = "";
    StringBuffer selected_text_buffer = new StringBuffer(selected_text_buff);
             
      void text_not_found_alert(Event event) {

            //{{CONNECTION
            // Create with title, show as modal... Get Applet Information
            {
                  Container theFrame = this;
                  do {
                        theFrame = theFrame.getParent();
                  } while ((theFrame != null) && !(theFrame instanceof Frame));
                  if (theFrame == null)
                        theFrame = new Frame();
                  (new AttentionDialog((Frame)theFrame, "Text not found.", true)).show();
            }
            //}}
      }
      
      void no_text_selected_to_replace_alert() {

            //{{CONNECTION
            // Create with title, show as modal... Get Applet Information
            {
                  Container theFrame = this;
                  do {
                        theFrame = theFrame.getParent();
                  } while ((theFrame != null) && !(theFrame instanceof Frame));
                  if (theFrame == null)
                        theFrame = new Frame();
                  (new AttentionDialog((Frame)theFrame, "Could not replace text as none was selected.", true)).show();
            }
            //}}
      }
      

      public void get_selected() {
            Object textArray[]; // array to hold JSObject stuff
            textArray = new Object[1]; // set array to hold only one object
            textArray[0] = text_entry.getSelectedText(); // assign array elements
            win.call("extract_text", textArray);        // to pass object array to Javascript
    }

      public void get_all() {
            Object textArray2[]; // array to hold JSObject stuff
            textArray2 = new Object[1]; // set array to hold only one number
            textArray2[0] = text_entry.getText(); // assign array elements
            win.call("extract_all", textArray2);        // to pass object array to Javascript
    }

      public void replace_selected() {
            back_up_JSchange(); // create back-up for undo
            String replacement_text = (String)win.eval("getReplacementText()"); // evaluates JavaScript expression that returns ReplacementText
            //if ((text_entry.getSelectionStart() - text_entry.getSelectionEnd()) == 0)
            //{
            text_entry.replaceText(replacement_text, text_entry.getSelectionStart(), text_entry.getSelectionEnd()); // replaces selected text
            //}
            //else
            //{
            //no_text_selected_to_replace_alert();    
            //}
   
    }

      public void insert_text() {
            back_up_JSchange(); // create back-up for undo
            String insert_string = (String)win.eval("getInsertText()");
            text_entry.insertText(insert_string, text_entry.getSelectionStart()); //inserts text at start point
    }

      public void append_text() {
            back_up_JSchange(); // create back-up for undo            
            String append_string = (String)win.eval("getAppendText()");
            text_entry.appendText(append_string); //appends string at end of text_entry
    }

    public void undo_JSchange() {
        String temp_string = text_entry.getText();
        text_entry.replaceText(text_entry_bak_buff.toString(),0 , temp_string.length());
    }
   
    public void select_all() {
        text_entry.select(0,text_entry.getText().length());
        text_entry.requestFocus();
    }

    void back_up_JSchange() {
        String temp_string = text_entry.getText();
        text_entry_bak_buff.setLength(temp_string.length());
       
        for (int i=0; i<temp_string.length(); i++)
            {
            text_entry_bak_buff.setCharAt(i, temp_string.charAt(i));  
            }    
      }  
       
                                     
      void back_up_JAVAchange() {          // through Element.blur() JavaScript command, backs up changes user has made directly in JAVA textarea. No LOST_FOCUS event for Applets, only canvases
          String temp_string = text_entry.getText();
        text_entry_bak_JAVA_buff.setLength(temp_string.length());
     
        for (int i=0; i<temp_string.length(); i++)
            {
            text_entry_bak_JAVA_buff.setCharAt(i, temp_string.charAt(i));  
            }    
      }


      public void init() {
            super.init();

            // Take out this line if you don't use symantec.itools.net.RelativeURL
        symantec.itools.lang.Context.setDocumentBase(getDocumentBase());

            //{{INIT_CONTROLS
            setLayout(null);
            addNotify();
            resize(597,169);
            text_entry = new java.awt.TextArea();
            text_entry.reshape(0,0,596,144);
            text_entry.setFont(new Font("Helvetica", Font.PLAIN, 12));
            add(text_entry);
            find_entry = new java.awt.TextField();
            find_entry.reshape(304,145,149,24);
            add(find_entry);
            find_button = new java.awt.Button("find");
            find_button.reshape(455,146,61,22);
            add(find_button);
            findagain_button = new java.awt.Button("find again");
            findagain_button.reshape(517,146,78,22);
            add(findagain_button);
            hint = new java.awt.Label("Use CTRL-X/C/V for Cut/Copy/Paste");
            hint.reshape(136,148,168,17);
            hint.setFont(new Font("Helvetica", Font.BOLD, 9));
            add(hint);
            select_all_button = new java.awt.Button("select all");
            select_all_button.reshape(63,145,68,22);
            add(select_all_button);
            undo_button = new java.awt.Button("clear");
            undo_button.reshape(2,146,60,21);
            add(undo_button);
            //}}

        // Get a reference to the Navigator Window
        try{
            win = JSObject.getWindow(this);
            }catch (Exception e){
                // Don't throw exception information away, print it.
                e.printStackTrace();
                }

      }

      public boolean handleEvent(Event event) {
            if (event.target == find_button && event.id == Event.ACTION_EVENT) {
                  findEntry_Clicked(event);
                  return true;
            }

            if (event.target == findagain_button && event.id == Event.ACTION_EVENT) {
                  findAgain_Clicked(event);
                  return true;
            }

            if (event.target == undo_button && event.id == Event.ACTION_EVENT) {
                  undobutton_Clicked(event);
                  return true;
            }

            if (event.target == select_all_button && event.id == Event.ACTION_EVENT) {
                  select_all_button_Clicked(event);
                  return true;
            }
                  return super.handleEvent(event);
      }

      void findEntry_Clicked(Event event) {

            //{{CONNECTION
            // Highlight the text to be found in the TextArea
            String find_str = find_entry.getText();
            int index = text_entry.getText().indexOf(find_str);
            
            if (index >= 0)
            {
                    text_entry.select(index, index + find_str.length());
                    text_entry.requestFocus();
                    get_selected();
            }
            else
            {
                  text_not_found_alert(event);
            //      return true;
            }
            //}}
      }

      void undobutton_Clicked(Event event) {
         String temp_string2 = text_entry.getText();
         text_entry.replaceText(text_entry_bak_JAVA_buff.toString() ,0 , temp_string2.length()); // replace text when undo
    }

    void select_all_button_Clicked(Event event) {
        text_entry.select(0,text_entry.getText().length());
        text_entry.requestFocus();
    }

      void findAgain_Clicked(Event event) {

            //{{CONNECTION
            // Highlight the text to be found in the TextArea
            String find_str = find_entry.getText();
        String temp_string3 = text_entry.getText();
        String searched_already = temp_string3.substring(0, text_entry.getSelectionEnd());
        String left_to_search = temp_string3.substring(text_entry.getSelectionEnd(), temp_string3.length());
 
              int index2 = left_to_search.indexOf(find_str);        
       
            if (index2 >= 0)
            {
                    text_entry.select(searched_already.length() + index2, searched_already.length() + index2 + find_str.length());
                    text_entry.requestFocus();
                    get_selected();
            }
            else
            {
                  text_not_found_alert(event);
            //      return true;
            }
                        
            //}}
      }


      //{{DECLARE_CONTROLS
      java.awt.TextArea text_entry;
      java.awt.TextField find_entry;
      java.awt.Button find_button;
      java.awt.Button findagain_button;
      java.awt.Label hint;
      java.awt.Button select_all_button;
      java.awt.Button undo_button;
      //}}
}

Got all that!
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1222160
OK, I notice that in replace_selected() you have a line that reads:

String replacement_text = (String)win.eval("getReplacementText()"); // evaluates JavaScript expression that returns ReplacementText

This lines makes me suspitious for various reasons:

1.- You are declaring replacement_text, but not instantiating it. There is no line that actualy creates the Sting object in the loacal heap, I.e.: no call to new().

2.- replacement_text exists exclusivley on the stack and is therfore suceptable to contain corrupted data. You need to initialize it.

Try:

String replacement_text = new (String);
replacement_text = "";
replacment_text = (String)win.eval("getReplacementText()");

Now, if this does not work, you might want to try running the applet with a debugger that allows you to single step through the code. If you don't have one, try downloading the Supercede trial version from:

http://www.supercede.com

or

http://asymetrix.com

Finally, if none of this works, send me an e-mail to:

jkelleghan@usa.net

with the source for the applet and the HTML file that contains the JavaScript and REMIND me what its about. I get arround 400 e-mails a day so I generaly skim through most that don't contain certain key phrases in the subject field. So put Experts-Exchange somwhere in the subject :-)
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:askrinsky
ID: 1222161
Visual Cafe does not seem to support the kind of instantiation you suggest.  It will allow me to:

String temp_string = "";

but not

String temp_string = new (String);

Any thoughts?
0
 
LVL 2

Accepted Solution

by:
mgk earned 400 total points
ID: 1222162
I am the friend who told Anthony that the AWT in JDK 1.0.2 counts line breaks and carriage returns incorrectly such that \n and \r are counted twice. I've encountered this problem when I wrote my JavaPad (http://www.powerup.com.au/~mgk/java/index.html).

Try this (I spent days/weeks on this by the way). I hope all the variable names are obvious enough:

selected=textarea.getSelectedText();
start=textarea.getSelectionStart();
end=textarea.getSelectionEnd();
if (System.getProperty("os.name").equals("Windows 95")) {
  for (i=0;i<start;i++){
    temp=textarea.getText();
    char c=temp.charAt(i);
    if (c=='\r') {
      start--;
      end--;
    }
  }
}

Cheers (Hi Anthony),

Mark King
0
 

Author Comment

by:askrinsky
ID: 1222163
Thank you both for all of your help!

I'm very appreciative,

Anthony
0
 

Author Comment

by:askrinsky
ID: 1222164
Unfortunately, neither solution works...

Could there be other characters besides /r that cause trouble.  The inclusion of /n does not help matters...

Instantiating isn't supported by Visual Cafe.. although I was able to set variables to '' initially.

Perhaps there is another creative approach!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

719 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