是否有任何函數可用於實際傳遞行號和字符串以突出顯示該行號中的單詞。我不知道如何實現這一目標。根據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");
}
}
}
請參見[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