Tah*_*ain 0 java arrays exception
异常消息:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Run Code Online (Sandbox Code Playgroud)
以下是我用来突出显示特定单词的代码JTextPane.我的目标是创建一个简单的语法高亮编辑器,我已经彻底搜索它并找到了许多有趣的解决方案,但我想为它编写自己的代码,现在我被困在了IndexOutOfBoundsException.
每当按下第三个键时,我的编辑器会给出此异常,这意味着每当写入2个字母时JTextPane.
如果代码不容易理解,我很抱歉,我是学习惯例的新手.
我知道这是一个非常微不足道的问题,但任何形式的帮助都是相当大的.谢谢 :)
[更新]代码的第一部分适用于jTextPane2KeyTyped事件
String[] words = new String[] {"if","else","for"};
//words is the list for words to change color
StyledDocument doc = jTextPane2.getStyledDocument();
Style style=doc.addStyle("Red_Colour", null);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setForeground(common,Color.BLACK);
String temp = jTextPane2.getText();
//temp holds the string value of the text present in the jTextPane2
int check=0;
for(int i=0;i<temp.length();i++){
for(int j=0;j<words.length;j++){
if(charLeft(temp,words,i,j)){
if(temp.length()>=words[j].length())
for(int k=0;k<words[j].length();k++){
if(temp.charAt(i+k)==words[j].charAt(k))check++;
}
//else{break;}
if(check==words[j].length()){
doc.setCharacterAttributes(i,words[j].length(),style, false);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是调用方法的代码(即charLeft())
public Boolean charLeft(String temp,String[] words,int i,int j){
temp= temp.substring(i, temp.length());
if(temp.length()<words[j].length())return true;
else return false;
}
Run Code Online (Sandbox Code Playgroud)
TrackBack的例外情况
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
at java.awt.Component.processEvent(Component.java:6282)
...
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
...
Run Code Online (Sandbox Code Playgroud)
你实际上j也是在第三个循环中递增,而不是k:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();j++)
Run Code Online (Sandbox Code Playgroud)
一个自发的猜测是你应该把它改成以下,以避免超过最大长度:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();k++)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1390 次 |
| 最近记录: |