2013-03-07 56 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)