StyledDocument为每行文件的indexof添加额外计数

时间:2012-07-15 06:46:53

标签: highlighting indexof styleddocument

我有一个奇怪的问题(至少看起来是这样的),当在textPane中搜索字符串时,我得到一个额外的索引,用于搜索和返回的每个行号,当使用StyledDoc时只是从文本中获取文本textPane。我从同一个窗格中获取相同的文本,只是一个来自纯文本,另一个来自样式文档。我在这里错过了一些东西。我将尝试列出我正在使用的两个版本之间的许多更改。

纯文本版本:

public int displayXMLFile(String path, int target){
    InputStreamReader inputStream;
    FileInputStream fileStream;
    BufferedReader buffReader;

    if(target == 1){

        try{                
            File file = new File(path);
            fileStream = new FileInputStream(file);
            inputStream = new InputStreamReader(fileStream,"UTF-8");
            buffReader = new BufferedReader(inputStream);
            StringBuffer content = new StringBuffer("");
            String line = "";
            while((line = buffReader.readLine())!=null){
                content.append(line+"\n");
            }
            buffReader.close();
            xhw.txtDisplay_1.setText(content.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }
}

与样式文档相对应(未应用样式)

    protected void openFile(String path, StyledDocument sDoc, int target) 
                throws BadLocationException {

    FileInputStream fileStream;
    String file;
    if(target == 1){
        file = "Openning First File";
    } else {
        file = "Openning Second File";
    }


    try {
        fileStream = new FileInputStream(path);

        // Get the object of DataInputStream
        //DataInputStream in = new DataInputStream(fileStream);

        ProgressMonitorInputStream in = new ProgressMonitorInputStream(
                xw.getContentPane(), file, fileStream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {                   
            sDoc.insertString(sDoc.getLength(), strLine + "\n", sDoc.getStyle("regular"));
        xw.updateProgress(target);
        } 

        //Close the input stream
        in.close();
    } catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

这是我搜索的方式:

    public int searchText(int sPos, int target) throws BadLocationException{

    String search = xhw.textSearch.getText();
    String contents;
    JTextPane searchPane;

    if(target == 1){
        searchPane = xhw.txtDisplay_1;              
    } else {
        searchPane = xhw.txtDisplay_2;
    }

    if(xhw.textSearch.getText().isEmpty()){
        xhw.displayDialog("Nothing to search for");
        highlight(searchPane, null, 0,0);
    } else {


        contents = searchPane.getText();

        // Search for the desired string starting at cursor position
        int newPos = contents.indexOf( search, sPos );

        // cycle cursor to beginning of doc window
        if (newPos == -1 && sPos > 0){
            sPos = 0;
            newPos = contents.indexOf( search, sPos );
        } 

        if ( newPos >= 0 ) {
            // Select occurrence if found

            highlight(searchPane, contents, newPos, target);

            sPos = newPos + search.length()+1;
        } else {
            xhw.displayDialog("\"" + search + "\"" + " was not found in File " + target);
        }
    } 
    return sPos;
}

示例文件:

<?xml version="1.0" encoding="UTF-8"?>
<AlternateDepartureRoutes>
  <AlternateDepartureRoute>
    <AdrName>BOIRR</AdrName>
    <AdrRouteAlpha>..BROPH..</AdrRouteAlpha>
    <TransitionFix>
      <FixName>BROPH</FixName>
    </TransitionFix>
  </AlternateDepartureRoute>
  <AlternateDepartureRoute>
</AlternateDepartureRoutes>

我的荧光笔:

    public void highlight(JTextPane tPane, String text, int position, int target) throws BadLocationException {
    Highlighter highlighter =  new DefaultHighlighter();
    Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY);
    tPane.setHighlighter(highlighter);

    String searchText = xhw.textSearch.getText();
    String document = tPane.getText();
    int startOfSString = document.indexOf(searchText,position);

    if(startOfSString >= 0){
        int endOfSString = startOfSString + searchText.length();
        highlighter.addHighlight(startOfSString, endOfSString, painter);
        tPane.setCaretPosition(endOfSString);
        int caretPos = tPane.getCaretPosition();
        javax.swing.text.Element root = tPane.getDocument().getDefaultRootElement();
        int lineNum = root.getElementIndex(caretPos) +1;
        if (target == 1){
            xhw.txtLineNum1.setText(Integer.toString(lineNum));
        } else if (target == 2){
            xhw.txtLineNum2.setText(Integer.toString(lineNum));
        } else {
            xhw.txtLineNum1.setText(null);
            xhw.txtLineNum2.setText(null);
        }

    } else {
        highlighter.removeAllHighlights();
    }

}

当我使用indexof()搜索Alt时,我得到40为纯文本(这应该返回)和41用样式文档搜索时。对于Alt出现的每个额外行,我得到额外的索引(以便indexof()调用返回2,然后在第3行中需要)。这会发现它找到的每一个额外的行。我错过了一些明显的东西吗(如果我需要将它推到一个较小的单个类,以便更容易检查,我可以在以后有更多时间时这样做。)

提前致谢...

2 个答案:

答案 0 :(得分:1)

如果你在Windows上,那么TextComponent文本(searchPane.getText())可以包含回车符+换行符(\ r \ n),但是TextComponent的样式文档(sSearchPane.getText(0,sSearchPane.getLength) ()))仅包含换行符(\ n)。这就是为什么你的newPos总是比newPosS大那个新线的数量。要解决此问题,您可以在搜索功能中更改:

contents = searchPane.getText();

为:

contents = searchPane.getText().replaceAll("\r\n","\n");

这样,搜索就会与样式文档使用的索引相同。

答案 1 :(得分:0)

好的我找到了一个解决方案(基本上)。我从两个不同的方式从同一个文本组件获取文本的方面接近了这个...

    String search = xw.textSearch.getText();
    String contents;
    String contentsS;
    JTextPane searchPane;
    StyledDocument sSearchPane;

    searchPane = xw.txtDisplay_left;
    sSearchPane = xw.txtDisplay_left.getStyledDocument();


    contents = searchPane.getText();
    contentsS = sSearchPane.getText(0, sSearchPane.getLength());

    // Search for the desired string starting at cursor position
    int newPos = contents.indexOf( search, sPos );
    int newPosS = contentsS.indexOf(search, sPos);

所以当比较两个变量“newPos”&amp; “newPosS”,对于找到搜索字符串的每一行,newPos再次为newPosS重新开始。因此,当查看示例文件并搜索“Alt”时,第一个实例在第2行找到。“newPos”返回41并且“newPosS返回40(然后突出显示正确的文本)。下一次出现(在行中找到) 3)“newPos”返回71并且“newPosS”返回69.正如您所看到的,每个新行都会增加计数的出现次数。我怀疑每个新行都会添加一个额外的字符来自StyledDoc中不存在的textPane。

我确信有合理的解释,但我现在还没有。