日期:2014-05-20  浏览次数:20788 次

帮忙分析一下这段代码!!!!
运行下面的程序出现了以下的情况
Java code
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1958)
    at java.lang.String.substring(String.java:1925)
    at java.awt.TextArea.replaceText(TextArea.java:390)
    at java.awt.TextArea.replaceRange(TextArea.java:377)
    at TextAreaDemo.<init>(TextAreaDemo.java:13)
    at TextAreaDemo.main(TextAreaDemo.java:29)



Java code
import java.awt.*;
public class TextAreaDemo extends Frame
{
TextArea textarea1=new TextArea(3,20);
TextArea textarea2=new TextArea("Second",3,15);
TextArea textarea3=new TextArea("Trid",2,10);
TextArea textarea4=new TextArea("Fourth",2,10,
TextArea.SCROLLBARS_BOTH);
TextArea textarea5=new TextArea(2,10);
TextAreaDemo()
{
    setLayout(new FlowLayout());
    textarea3.replaceRange("HelloWorld",0 ,5);
    textarea4.insert(" ", 3);
    textarea5.append("Fifth");
    
    add(textarea1);
    add(textarea2);
    add(textarea3);
    add(textarea4);
    add(textarea5);
    setSize(400,200);
    this.setVisible(true);
    
}
     
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new TextAreaDemo();

    }

}

 


------解决方案--------------------
TextArea textarea3=new TextArea("Trid",2,10);
初始值是Trid
textarea3.replaceRange("HelloWorld",0 ,5);
从第0个到第5个之间的内容,替换成HelloWorld,问题是Trid不够长啊!怎么截取?