gpt4 book ai didi

java - 突出显示在框架中打开的文本文件中的几个单词

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:30:21 25 4
gpt4 key购买 nike

我正在一个框架中打开一个文件,我想突出显示几个词。据我所知,我需要遍历文件的内容。我如何遍历内容以及我可以使用哪些相关属性来突出显示?


更新:我的代码是这样的


private JEditorPane editorpane;
JScrollPane editorScrollPane;

public TextEditor()
{
editorpane = new JEditorPane();
editorpane.setEditable(false);

if (filename != null)
{
try
{
File file = new File(filename);
editorpane.setPage(file.toURI().toURL());
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("Attempted to read a bad file ...");
}
}
else
{
System.err.println("File name is wrong");
}

add(editorpane);
}

最佳答案

要在 JEditorPane 上突出显示,请查看以下示例:

enter image description here

import java.awt.Color;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class Test {

// An instance of the subclass of the default highlight painter
static MyHighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JEditorPane jep = new JEditorPane();
jep.setText("Hello to the public");
frame.add(jep);
frame.pack();
frame.setVisible(true);

highlight(jep, "public");//'public is the word to highligh'

}
});
}

// Creates highlights around all occurrences of pattern in textComp
public static void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
removeHighlights(textComp);

try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;

// Search for pattern
while ((pos = text.indexOf(pattern, pos)) >= 0) {
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}

// Removes only our private highlights
public static void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();

for (int i = 0; i < hilites.length; i++) {
if (hilites[i].getPainter() instanceof MyHighlightPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
}

class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

public MyHighlightPainter(Color color) {
super(color);
}
}

关于java - 突出显示在框架中打开的文本文件中的几个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com