gpt4 book ai didi

java - 如何更改 JEditorPane 中 HTML 文档的特定元素的颜色?

转载 作者:行者123 更新时间:2023-11-30 06:39:37 24 4
gpt4 key购买 nike

我基本上想实现在将鼠标悬停在链接上时更改链接的颜色。当我将鼠标悬停在链接上时触发的 HyperlinkEvent 将 HTML 元素交给我,但它不允许我在其上设置任何样式属性,而且我不知道如何获取具有可设置属性的元素。

最佳答案

我想通了使用样式化文档和 HTMLEditorKit 的一些帮助我想做什么:

public class HighlightHyperlinkExample {
private static Element lastHyperlinkElementEntered;
private static JEditorPane textPane;


public static void main(String[] args) {
textPane = new JEditorPane();
textPane.setContentType(new HTMLEditorKit().getContentType());
JScrollPane scrollPane = new JScrollPane(textPane);
textPane.setText(
"Sample text with <a href=\"x\">a link</a> and another <a href=\"x\">link</a>.");

initListeners();

JFrame frame = new JFrame();
frame.add(scrollPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}


private static void initListeners() {
textPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
removeHyperlinkHighlight();
}
});
textPane.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}

public void mouseMoved(MouseEvent e) {
Point pt = new Point(e.getX(), e.getY());
int pos = textPane.viewToModel(pt);
if (pos >= 0) {
HTMLDocument hdoc = (HTMLDocument) textPane.getDocument();
Element elem = hdoc.getCharacterElement(pos);
if (elem != null) {
AttributeSet a = elem.getAttributes();
AttributeSet anchor = (AttributeSet) a.getAttribute(HTML.Tag.A);
if (anchor != null) {
//only highlight anchor tags
highlightHyperlink(elem);
} else {
removeHyperlinkHighlight();
}
}
}
}
});
}

private static void removeHyperlinkHighlight() {
changeColor(lastHyperlinkElementEntered, Color.BLUE);
lastHyperlinkElementEntered = null;
}

private static void highlightHyperlink(Element hyperlinkElement) {
if (hyperlinkElement != lastHyperlinkElementEntered) {
lastHyperlinkElementEntered = hyperlinkElement;
changeColor(hyperlinkElement, Color.RED);
}
}

private static void changeColor(Element el, Color color) {
if (lastHyperlinkElementEntered != null) {
HTMLDocument doc = (HTMLDocument) textPane.getDocument();
int start = el.getStartOffset();
int end = el.getEndOffset();
StyleContext ss = doc.getStyleSheet();
Style style = ss.addStyle("HighlightedHyperlink", null);
style.addAttribute(StyleConstants.Foreground, color);
doc.setCharacterAttributes(start, end - start, style, false);
}
}
}

关于java - 如何更改 JEditorPane 中 HTML 文档的特定元素的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/634296/

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