2013-03-07 57 views
0

是否有任何函数可用于实际传递行号和字符串以突出显示该行号中的单词。我不知道如何实现这一目标。根据JtextArea中的给定行号突出显示一个字符串

能够在JtextArea上加载我的文件。

文件加载时 “hello.txt的” 载:

Hello, This 
is my first 
lesson in Java 
Hope You Have a nice 
Time. 

我希望函数一致强调字符串 “第一个” 1

我的代码:

import javax.swing.*; 

import java.util.*; 

import java.io.*; 

public class OpenTextFileIntoJTextArea 
{ 
public static void main(String[]args) 
{ 
try 
{ 

    FileReader readTextFile=new FileReader("C:\\Hello.py"); 

    Scanner fileReaderScan=new Scanner(readTextFile); 

    String storeAllString=""; 

    while(fileReaderScan.hasNextLine()) 
    { 
    String temp=fileReaderScan.nextLine()+"\n"; 

    storeAllString=storeAllString+temp; 
    } 
    JTextArea textArea=new JTextArea(storeAllString); 
    textArea.setLineWrap(true); 
    textArea.setWrapStyleWord(true); 
    JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
    JFrame frame=new JFrame("Open text file into JTextArea"); 
    frame.add(scrollBarForTextArea); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(500,500); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 
catch(Exception exception) 
{ 

    System.out.println("Error in file processing"); 
} 
} 
} 
+0

请参见[this](http://stackoverflow.com/questions/13074428/how-can-i-set-each-character-to- a-different-color-background-color-in-a-jtextpan/13076649#13076649)example and its [variation](http://stackoverflow.com/questions/12481698/highlighting-few-of-the-words-of -a-文本文件打开功能于一帧/ 12482171#12482171)。也可以阅读[Siwng中的并发](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html),并且不要在'JFrame'上调用'setSize'使用适当的'LayoutManager'并且/或重写'getPreferredSize()'并在'JFrame'上调用'pack()',然后将其设置为可见。 – 2013-03-07 17:19:10

回答

2

从JTextArea的方法开始:

  1. 请参阅getLineStartOffset(...)getLineEndOffset(...)方法。
  2. 然后您可以使用getText(...)方法获取该行的所有文本。
  3. 然后您可以使用String.indexOf(...)搜索“first”位置的文本。
  4. 现在你可以添加从该行的开始和的indexOf方法的偏移量来获得您想要的文档中突出显示文本的位置
  5. 那么你可以使用文本区域的getHighlighter()方法来获取荧光笔
  6. 终于可以使用addHighlight()方法来突出这个词
+0

我可以通过使用您在步骤中描述的代码向我展示一个Java新手。谢谢 – 2013-03-07 17:32:37

+0

我会开始创建一个像'highlightText(textArea,row,text)'这样的方法。然后在该方法中,您尝试一次一步地实现代码。 – camickr 2013-03-07 17:55:13

0

你尝试过用打转转:

JTextComponent.setSelectionStart(INT), JTextComponent.setSel ectionEnd(int), JTextComponent.setSelectedTextColor(java.awt.Color)